When using WCF, we can define a service contract:
[ServiceContract]
public interface IMyService
{
[OperationContract]
int MyOperation(int x);
}
Assume I open a servicehost at www.example.com/MyService
, then one way to use this service from my client is
IMyService service =
new ChannelFactory<IMyService>(new BasicHttpBinding(),
new EndpointAddress("www.example.com/MyService")).CreateChannel();
int result = service.MyOperation(10);
So somehow, service
implements IMyService
, although that was never done explicitly. If I debug these lines, I can see that service
is an instance of __TransparentProxy
. As you can see from the source code, the comments in that class say
Transparent proxy magically creates a message that represents a call on it and delegates to the Real proxy to do the real remoting work.
To me this is indeed 'magic', but I guess there must be a logical explanation.
The pattern here can be very useful. What I would like is some class like Magic
below (the syntax is incorrect, I know, otherwise I wouldn't need to ask). For the sake of argument, let's say I want this class to print the name of the method called.
public class Magic<T> : T {
// don't know what to do here
}
Such that I would be able to call
IMyService service = new Magic<IMyService>();
service.MyOperation(10);
And this would print:
MyOperation
Is something like this possible? (It should be, since __TransparentProxy
does something similar.) And if so, how would this work?
There are a few articles on Codeplex that try to do something similar to what WCF does under the covers:
http://www.codeproject.com/Articles/43598/Emit-Proxy http://www.codeproject.com/Articles/5511/Dynamic-Proxy-Creation-Using-C-Emit
The System.Reflection.Emit
namespace is the underlying key, which can be used to dynamically create .NET assemblies and types in code.