这是不可能的,因为每个方法都会为绑定的所有实例创建一个拦截器。
但是你可以做的不是直接在拦截器中执行拦截代码,而是获取一个将处理拦截的类的实例。
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);