有没有办法可以将 AutoFac 设置为使用 PropertiesAutowired(true) 作为所有注册类型的默认值。
即我不想一直使用“.PropertiesAutowired(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);
};
}
}
然后:
builder.RegisterModule<InjectPropertiesByDefaultModule>();
我认为您可能误解了 PropertiesAutowired
的 true
参数 - 它决定了如何支持循环依赖,并且可能应该保持 false
。要模拟 true
设置,您可以附加到 Activated
而不是上面的 Activating
。
但是,如果可能的话,即使对于像 ILog
这样的“可选”依赖项,也要使用构造函数注入(inject)。它导致组件更简洁(例如,可以将字段设置为 readonly
)并且依赖项更易于理解(它们都在构造函数中,并且无需猜测各个属性的含义。)
仅当应用程序有多个配置时才考虑使用属性注入(inject),并且在某些配置中确实不存在依赖项。
即使在这些情况下,“Null Object”模式通常更适合。
关于.net - 将 AutoFac 设置为默认使用 PropertiesAutowired(true)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3384812/