Reputation: 25039
I use Ninject. The injected property of self-binded class is not resolved when the class has an interceptor. Up-to-date libraries are used:
<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
class is self-binded:
public class Foo
{
[Inject]
public IBar Bar { get; set; }
}
public interface IBar
{
void MyMethod();
}
public class Bar : IBar
{
public void MyMethod() { }
}
The interceptor:
public class TestInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
}
}
And two tests:
[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
is successful. Test2
fails. Why? Is it expected behavior?
Upvotes: 1
Views: 83
Reputation: 27871
It would work if you make the Bar
property virtual
like this:
public class Foo
{
[Inject]
public virtual IBar Bar { get; set; }
}
Upvotes: 1