拦截器中断属性注入



我使用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失败。为什么?这是预期行为吗?

如果您将Bar属性virtual如下所示,它将起作用:

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

最新更新