在使用ServiceStack及其IoC/DI框架时,遇到如下问题:
DI 框架将 null 注入(inject)到属性中,并且该属性类型未在容器中注册。
class DependencyInjectedA : IDependencyInjectedA
{
public DependencyInjectedB { get; set; }
}
class DependencyInjectedB
{
public Dictionary<DateTime, SomeClass> MyProperty { get; set; }
}
在我的 Configure 方法中:
public override void Configure(Container container)
{
base.Configure(); // here we have code like 'Container.AutoWire(this);'
container.AddSingleton<IDependencyInjectedA, DependencyInjectedA>();
container.AddSingleton<DependencyInjectedB>();
}
所以,在父类中,我做
Container.AutoWire(this);
AutoWire 调用背后的原因是我可以获得 DI 框架来注入(inject) this
的后代。 .我的印象是只有在 Container 中注册的类型才会被依赖注入(inject),而且它是 this
的后代。 , 但似乎也是 MyProperty
在DependencyInjectedB
被注入(inject),然后是 null
值,因为我们没有添加 Dictionary<DateTime, SomeClass>
到容器。
这是一张(经过一些编辑的)图片,说明发生了什么:当我认为它不应该这样做时,DI 注入(inject)了 NULL。
神话其实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.
问题:
- 我怎样才能拥有不想被注入(inject)的公共(public)属性?
- 有没有办法只注入(inject)容器中注册的类型 (.AddXXX)?
最佳答案
这是 Funq's autowiring 的行为既进行公共(public)属性(property)注入(inject)又进行构造函数注入(inject)。
特别是 Funq 的 Autowiring 行为将注入(inject)任何属性:
- 公开
- 可写(即有一个公共(public) setter)
- 不是ValueType 或string
- 它的完整类型名称未在
Container.IgnorePropertyTypeFullNames
集合中注册
因此,如果您不想注入(inject)属性,它们就无法满足上述所有条件。如果您只想防止注入(inject)一个属性类型,您可以在以下位置注册完整的类型名称:
Container.IgnorePropertyTypeFullNames.Add(typeof(DependencyInjectedB).FullName);
或者将其更改为不public
,否则您不应该使用Funq's AutoWiring APIs包含此行为,您将改为使用自定义工厂函数注册依赖项,例如:
container.AddSingleton<IDependencyInjectedA>(c => new DependencyInjectedA());
关于dependency-injection - 服务堆栈国际奥委会。 AutoWire(this) 尝试注入(inject)未在容器中注册的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65339147/