我使用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
失败了。为什么?这是预期的行为吗?
答案 0 :(得分:1)
如果您像这样制作Bar
属性virtual
,那将会有效:
public class Foo
{
[Inject]
public virtual IBar Bar { get; set; }
}