当存在多个绑定时,选择错误的拦截器

时间:2014-01-14 16:22:16

标签: ninject ninject-interception

我有多个接口实现,我想为每个接口应用不同的拦截器,例如:

public interface IFoo { int Run(); }

public class Foo1 : IFoo
{
    public int Run() { return 1; }
}

public class Foo2 : IFoo
{
    public int Run() { return 2; }
}

拦截器示例:

public class MultiplyBy10 : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        invocation.ReturnValue = (int)invocation.ReturnValue * 10;
    }
}

public class MultiplyBy100: IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        invocation.ReturnValue = (int)invocation.ReturnValue * 100;
    }
}

结合:

var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo1>().Named("1");
kernel.Bind<IFoo>().To<Foo2>().Named("2");

kernel.Intercept(ctx => ctx.Plan.Type == typeof(Foo1)).With<MultiplyBy10>();
kernel.Intercept(ctx => ctx.Plan.Type == typeof(Foo2)).With<MultiplyBy100>();

我希望Foo1乘以10而Foo2乘以100.但是两者都乘以10,即:

var foo1 = kernel.Get<IFoo>(ctx => ctx.Name == "1");
var foo2 = kernel.Get<IFoo>(ctx => ctx.Name == "2");

Assert.That(foo1.Run(), Is.EqualTo(10));
// fails: returns 20
Assert.That(foo2.Run(), Is.EqualTo(200));

这是一个错误还是我做错了什么?

1 个答案:

答案 0 :(得分:0)