An example explains it best :
public interface IA {
void foo();
void bar();
}
public class A : IA {
public virtual void foo(){
Console.Write("foo");
bar(); //call virtual method
}
public virtual void bar(){
Console.Write("bar");
}
}
public class Interceptor : IInterceptor {
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Intercepted: " + invocation.Method.Name);
invocation.Proceed();
}
}
Main(){
IA a = new A();
//proxy-ing an interface, given an implementation
IA proxy = new Castle.DynamicProxy.ProxyGenerator()
.CreateInterfaceProxyWithTarget(a, new Interceptor());
proxy.foo();
}
I would have expected the output:
Intercepted foo
foo
Intercepted bar
bar
Instead, I get:
Intercepted foo
foo
bar
Why?
How does the dynamic proxy work?
I was expecting the generated proxy to inherit from the proxied class, however, it seems that it uses composition to delegate each of the methods in the proxied interface to the actual implementation.
I've tried with Castle DynamicProxy and also with an older dynamic proxy implementation, from Cramon
Best Answer
Looks like my guess was right.
I tried the same example, only this time creating the proxy directly from the class type:
The result was what I expected in the first place:
This leads me to the following conclusion:
When creating an interface proxy with an interface implementation, the generated proxy looks something like this:
When creating a class proxy, the code looks like this: