[英]How use IInterceptor in Castle.DynamicProxy?
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 实现了DynamicProxy提供的“ IInterceptor”
[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 创建一个Interceptor类,并从“ Interceptor”类继承
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. 尝试使方法
Add
虚拟。
public class Calculator
{
public virtual int Add(int a, int b)
{
return a + b;
}
}
The proxy generator creates a new class inheriting Calculator
. 代理生成器创建一个继承
Calculator
的新类。 Thus, the method Add
gets an override to make interception possible. 因此,方法
Add
获得重写以使拦截成为可能。
The other option is to make an ICalculator interface 另一个选择是制作一个ICalculator接口
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 然后,您的动态代理将使用CreateInterfaceProxyWithTarget方法
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. 这摆脱了您的Calculator类中的虚函数,我认为这是不好的设计,除非您将来有理由重写该方法。
You have to use the correct overload and pass in both the target object and the interceptor you wish to use. 您必须使用正确的重载,并传入您要使用的目标对象和拦截器。 Method should look something like this:
方法应如下所示:
var proxy = generator.CreateClassProxy<Calculator>(new Calculator(), new CalculatorInterceptor() );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.