属性 Ninject 中的注入无效

Property injection in Ninject is not working

我有这样一个class

public sealed class SimpleTextIndex<T> : TextIndex where T : ITextParser
{
    [Inject]
    public T TextParser { get; set; }
    // something...

以及依赖解析方法

public void Resolve() 
{
    Kernel = new StandardKernel();
    Kernel.Bind(typeof(ITextParser)).To(typeof(WordTextParser));
    Kernel.Bind(typeof(SimpleTextIndex<>)).ToSelf();
}

WordTextParser 是一个 class,它实现了 ITextParser 接口。 但是,在调用 Resolve() 方法和内核的 Get() 方法之后:

var textIndex = kernel.Get<SimpleTextIndex<ITextParser>>();

我收到 NullReferenceException(SimpleTextIndex 中的 TextParser 属性 为空)! 但是,如果我以这种方式为 SimpleTextIndex 编写默认构造函数:

public SimpleTextIndex()
{
  DependencyResolver.Kernel.Inject(this);
}

一切正常!为什么?

问题是属性注入只有在通过构造函数构造对象后才进行,即Ninject无法在构造函数完成之前设置属性值。

由于您使用的是从构造函数调用的方法的依赖项,因此 属性 尚未设置,因此其值为 null。

要么在构建过程中不使用依赖关系,要么像这样使用构造函数注入:

//[Inject] //remove this attribute
public T TextParser { get; set; }

public SimpleTextIndex(T parser, string text = "")
{
    TextParser = parser;
    ...
}