I wrote an example like this
Simple Calculator class :
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
implemented "IInterceptor" that provided by DynamicProxy
[Serializable]
public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}
Created an Interceptor class and inherited from "Interceptor" class
public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Start");
}
protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("End");
}
}
but when I used it NOT working !!!
static void Main(string[] args)
{
ProxyGenerator generator = new ProxyGenerator();
Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
var r = c.Add(11, 22);
Console.WriteLine(r);
Console.ReadKey();
}
I excepted to see something like this :
START
33
END
but only show
33
How I can correct it ?!
Try to make the method Add
virtual.
public class Calculator
{
public virtual int Add(int a, int b)
{
return a + b;
}
}
The proxy generator creates a new class inheriting Calculator
. Thus, the method Add
gets an override to make interception possible.
The other option is to make an ICalculator interface
public interface ICalculator
{
int Add(int a, int b);
}
and inherit your class from this interface
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Your dynamic proxy would then use the CreateInterfaceProxyWithTarget method
var proxyGenerator = new ProxyGenerator();
ICalculator calculator = new Calculator()
var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(
calculator,
ProxyGenerationOptions.Default,
new CalculatorInterceptor());
Console.WriteLine(proxy.Add(1, 2));
This gets rid of the virtual from your Calculator class, which in my opinion is bad design unless you have reason to override the method in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With