拦截器打破属性注入

时间:2016-01-19 16:38:43

标签: c# dependency-injection ninject

我使用Ninject。当类具有拦截器时,自绑定类的注入属性不会被解析。使用最新的库:

  <package id="Castle.Core" version="3.2.0" targetFramework="net46" />
  <package id="Ninject" version="3.2.0.0" targetFramework="net46" />
  <package id="Ninject.Extensions.Interception" version="3.2.0.0" targetFramework="net46" />
  <package id="Ninject.Extensions.Interception.DynamicProxy" version="3.2.0.0" targetFramework="net46" />

Foo课程是自我绑定的:

public class Foo
{
    [Inject]
    public IBar Bar { get; set; }
}

public interface IBar
{
    void MyMethod();
}

public class Bar : IBar
{
    public void MyMethod() { }
}

拦截器:

public class TestInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
    }
}

两个测试:

[Test]
public void Test1()
{
    var kernel = new StandardKernel();

    kernel.Bind<IBar>().To<Bar>();
    kernel.Bind<Foo>().ToSelf();

    var foo = kernel.Get<Foo>();

    Assert.IsNotNull(foo.Bar);
}

[Test]
public void Test2()
{
    var kernel = new StandardKernel();

    kernel.Bind<IBar>().To<Bar>();
    kernel.Bind<Foo>().ToSelf().Intercept().With<TestInterceptor>(); //the only diff

    var foo = kernel.Get<Foo>();

    Assert.IsNotNull(foo.Bar);
}

Test1成功。 Test2失败了。为什么?这是预期的行为吗?

1 个答案:

答案 0 :(得分:1)

如果您像这样制作Bar属性virtual,那将会有效:

public class Foo
{
    [Inject]
    public virtual IBar Bar { get; set; }
}