Let’s say that I have the following interface:
public interface IMyService
{
void SimpleMethod(int id);
int Hello(string temp);
}
And want to generate a class that looks like this (using reflection emit).
public class MyServiceProxy : IMyService
{
IChannel _channel;
public MyServiceProxy(IChannel channel)
{
_channel = channel;
}
public void SimpleMethod(int id)
{
_channel.Send(GetType(), "SimpleMethod", new object[]{id});
}
public int Hello(string temp)
{
return (int)_channel.Request(temp);
}
}
How do I do it? I’ve checked various dynamic proxies and mock frameworks. They are bit complex and not very easy to follow (and I do not want an external dependency). It shouldn’t be that hard to generate a proxy for an interface. Can anyone show me how?
All in all I’m going to agree with others’ comments. I’ve used Castle’s DynamicProxy and I think it’s wonderful. You can do some really amazing and powerful stuff with it. That said, if you’re still considering writing your own, read on:
If you’re not excited about emitting IL, there are some new techniques using Lambda expressions that you can use to generate code. None of this is a trivial task, however.
Here’s an example of how I’ve used Lambda expressions to generate a dynamic event handler for any .NET event. You could use a similar technique to generate a dynamic interface implementation.
Regards,
-Doug