views:

215

answers:

2

Is there a way to create a proxy of a delegate type and have it implement additional interfaces in DynamicProxy2 and also being able to intercept calls to the generated delegate?

The way i normaly generate proxies throws an exception because delegate types are sealed.

A: 

delegate types are created at compile time by generating a sealed subclass of MulticastDelegate (see: http://msdn.microsoft.com/en-us/magazine/cc301816.aspx).

AFAIK DynamicProxy2 only works by subclassing types, and so this isn't going to be possible.

There seems to be some technology in Typemock Isolator that can mock sealed classes, but I've not used it and it isn't free, so your mileage my vary.

DLKJ
I'm fairly sure that Rhino Mocks uses DynamicProxy to create proxies of delegates so I _think_ it's possible, I just don't know how. I guess I could check the source of Rhino Mocks though.
Patrik Hägne
Why do you need to mock a delegate? Could you post an example of what you are trying to achieve?
DLKJ
I don't mention in my question that I want to mock it, I want to proxy it so that I can intercept calls to it. But you're right, it has to do with mocking. I have a personal project that's a new mock framework and I want it to have the feature of being able to fake delegate types. This is why I'm very reluctant to look at the codebase of for example Rhino since I don't want to "steal" anything. http://code.google.com/p/fakeiteasy/
Patrik Hägne
A: 

Patrik,

You don't need DynamicProxy to 'proxy' delegates This should be enough:

Action delegateToproxy = new Foo().Bar; //Bar is public void Bar(){}
Action proxy = delegate
               {
                  Console.WriteLine("Intercepted!");
                  delegateToProxy();
               }
return proxy;

[UPDATE: that aswer was not relevant to this specific problem] What kind of API do you want to expose for this?

If you want to follow up with this conversation please contact me via email, or start a thread on Castle users group.

Krzysztof Koźmic
As you say in your update, this is only half way there, the problem that remains is that I can't have it implement any extra interfaces. I will mark this answer as the accepted one though since it's a good answer in the general case.
Patrik Hägne