我当前遇到一个问题,尝试为每个被拦截的类实例连接一个拦截器实例。
我正在 InterceptorRegistrationStrategy 中创建 Advice 并设置回调以解析来自内核的拦截器(它有一个注入(inject)构造函数)。请注意,我只能在回调中实例化拦截器,因为 InterceptorRegistrationStrategy 没有引用 Kernel 本身。
IAdvice advice = this.AdviceFactory.Create(methodInfo);
advice.Callback = ((context) => context.Kernel.Get<MyInterceptor>());
this.AdviceRegistry.Register(advice);
我正在为每个方法获取一个拦截器实例。
有没有办法为每个被拦截的类型实例创建一个拦截器实例?
我正在考虑命名范围,但拦截类型和拦截器并不互相引用。
最佳答案
这是不可能的,因为为绑定(bind)的所有实例的每个方法创建一个拦截器。
但是您可以做的不是直接在拦截器中执行拦截代码,而是获取将处理拦截的类的实例。
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);
关于ioc-container - Ninject:每个被拦截的类实例有一个拦截器实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353476/