我目前遇到一个问题,尝试为每个被拦截的类实例连接一个拦截器实例。
我正在 InterceptorRegistrationStrategy 中创建 Advice 并设置回调以解析来自内核的拦截器(它有一个注入构造函数)。请注意,我只能在回调中实例化拦截器,因为 InterceptorRegistrationStrategy 没有引用 Kernel 本身。
IAdvice advice = this.AdviceFactory.Create(methodInfo);
advice.Callback = ((context) => context.Kernel.Get<MyInterceptor>());
this.AdviceRegistry.Register(advice);
我得到每个方法的拦截器实例。
有没有办法为每个被拦截的类型实例创建一个拦截器实例?
我正在考虑命名范围,但拦截类型和拦截器不互相引用。
这是不可能的,因为为绑定的所有实例的每个方法创建一个拦截器。
但是您可以做的不是直接在拦截器中执行拦截代码,而是获取将处理拦截的类的实例。
public class LazyCountInterceptor : SimpleInterceptor
{
private readonly IKernel kernel;
public LazyCountInterceptor(IKernel kernel)
{
this.kernel = kernel;
}
protected override void BeforeInvoke(IInvocation invocation)
{
this.GetIntercpetor(invocation).BeforeInvoke(invocation);
}
protected override void AfterInvoke(IInvocation invocation)
{
this.GetIntercpetor(invocation).AfterInvoke(invocation);
}
private CountInterceptorImplementation GetIntercpetor(IInvocation invocation)
{
return this.kernel.Get<CountInterceptorImplementation>(
new Parameter("interceptionTarget", new WeakReference(invocation.Request.Target), true));
}
}
public class CountInterceptorImplementation
{
public void BeforeInvoke(IInvocation invocation)
{
}
public void AfterInvoke(IInvocation invocation)
{
}
}
kernel.Bind<CountInterceptorImplementation>().ToSelf()
.InScope(ctx => ((WeakReference)ctx.Parameters.Single(p => p.Name == "interceptionTarget").GetValue(ctx, null)).Target);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)