Cor*_*ndt 2 ninject ioc-container interceptor ninject-2 ninject-extensions
我目前遇到了一个问题,试图在每个被拦截的类实例中连接一个拦截器实例.
我正在InterceptorRegistrationStrategy中创建和建议并设置回调来解析内核中的拦截器(它有一个注入构造函数).请注意,我只能在回调中实例化拦截器,因为InterceptorRegistrationStrategy没有引用内核本身.
IAdvice advice = this.AdviceFactory.Create(methodInfo);
advice.Callback = ((context) => context.Kernel.Get<MyInterceptor>());
this.AdviceRegistry.Register(advice);
Run Code Online (Sandbox Code Playgroud)
我正在获得每个方法的拦截器实例.
是否有任何方法可以为每个被拦截的类型实例创建一个拦截器实例?
我在考虑命名范围,但截获的类型和拦截器不会互相引用.
这是不可能的,因为每个方法为绑定的所有实例创建一个单一的拦截器.
但是你可以做的不是直接在拦截器中执行拦截代码,而是获取将处理拦截的类的实例.
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1137 次 |
| 最近记录: |