服务堆栈国际奥委会。 AutoWire(this) 尝试注入 public 未在容器中注册的属性

ServiceStack IOC. AutoWire(this) tries to inject public properties that are not registered in the Container

在使用ServiceStack及其IoC/DI框架时,遇到以下问题:

DI 框架将 null 注入 属性,并且 属性 类型未在容器中注册。

class DependencyInjectedA : IDependencyInjectedA
{
    public DependencyInjectedB { get; set; }
}

class DependencyInjectedB 
{
    public Dictionary<DateTime, SomeClass> MyProperty { get; set; }
}

在我的配置方法中:

public override void Configure(Container container)
{
    base.Configure(); // here we have code like 'Container.AutoWire(this);'
    container.AddSingleton<IDependencyInjectedA, DependencyInjectedA>();
    container.AddSingleton<DependencyInjectedB>();
}

所以,在父 class 中,我

Container.AutoWire(this);

调用 AutoWire 的原因是为了让 DI 框架注入 this 的后代。我的印象是只有在容器中注册的类型才会被依赖注入,而且它会是 this 的后代,但似乎 DependencyInjectedB 中的 MyProperty被注入,然后带有 null 值,因为我们还没有将 Dictionary<DateTime, SomeClass> 添加到容器中。

这是一张发生了什么的图片(经过一些编辑):当我认为它不应该这样做时,DI 注入了 NULL。

实际上Mythz says it here:

Autowire Registration You can register dependencies so that all the dependencies are automatically auto-wired. Just like the hooks above, once resolved Funq will create a new instance resolving dependencies for the constructor that has the most arguments as well as all public properties.

问题:

这是 Funq's autowiring 的行为,它同时执行 public 属性 和构造函数注入。

特别是 Funq 的自动装配行为将注入任何属性:

  • public
  • 可写(即有一个publicsetter)
  • 不是 ValueTypestring
  • 它的完整类型名称未在 Container.IgnorePropertyTypeFullNames 集合中注册

因此,如果您不想注入属性,它们就无法满足上述所有条件。如果只是一个 属性 类型,你想防止注入,你可以注册完整的类型名称:

Container.IgnorePropertyTypeFullNames.Add(typeof(DependencyInjectedB).FullName);

或者更改它,使其不是 public,否则您不应该使用包含此行为的 Funq's AutoWiring APIs,而是使用自定义工厂函数注册依赖项,例如:

container.AddSingleton<IDependencyInjectedA>(c => new DependencyInjectedA());