有没有办法我可以将 AutoFac 设置为使用 PropertiesAutowired(true) 作为所有注册类型的默认值。
即我不想一直使用“.Properties Autowired(true)”
var builder = new ContainerBuilder();
builder.RegisterType<Logger>()
.PropertiesAutowired(true)
.SingleInstance();
这可以通过模块来完成,例如
class InjectPropertiesByDefaultModule : Autofac.Module {
protected override void AttachToComponentRegistration(
IComponentRegistration registration,
IComponentRegistry registry) {
registration.Activating += (s, e) => {
e.Context.InjectProperties(e.Instance);
};
}
}
Then:
builder.RegisterModule<InjectPropertiesByDefaultModule>();
我想你可能误解了true
参数为PropertiesAutowired
- 它决定如何支持循环依赖并且可能应该保留false
。为了效仿true
您可以附加到的设置Activated
代替Activating
above.
但是,如果可能的话,即使对于像您这样的“可选”依赖项也可以使用构造函数注入ILog
。它会导致更清洁的组件(例如,可以将字段readonly
)和依赖项更容易理解(它们都在构造函数中,并且无需猜测各个属性的含义。)
仅当应用程序有多种配置并且在某些配置中真正不存在依赖性时才考虑使用属性注入。
即使在这些情况下,“空对象”模式通常更适合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)