问题描述
有没有一种方法我可以设置AutoFac使用PropertiesAutowired(真),以对被注册的所有类型的默认。
即。我不想使用.PropertiesAutowired(真)的所有时间
VAR建设者=新ContainerBuilder();
builder.RegisterType<记录仪>()
.PropertiesAutowired(真)
.SingleInstance();
这可以用一个模块完成,如:
类InjectPropertiesByDefaultModule:Autofac.Module {
保护覆盖无效AttachToComponentRegistration(
IComponentRegistration登记,
IComponentRegistry注册表){
registration.Activating + =(S,E)=> {
e.Context.InjectProperties(e.Instance);
};
}
}
然后:
builder.RegisterModule< InjectPropertiesByDefaultModule>();
我想你可能会误会真
paramerter到 PropertiesAutowired
- 它决定了循环依赖的支持,并应可能保持假
。为了模拟真
设置,您可以连接到激活
而不是激活
以上。
不过,如果可能的话,使用构造函数注入甚至是可选的依赖就像你的的ILog
。这导致了更清洁的部件(如字段可以由只读
)和相关性是更容易理解(他们都在构造函数,而且也没有猜测各个属性的含义。)
只考虑使用属性注入,当有应用的多种配置,在一些配置的依赖将是真正的缺席。
即使在这些情况下,空对象的图案通常是更好的选择。
Is there a way i can set AutoFac to use PropertiesAutowired(true) to be the default for all types being registered.
i.e. I dont want to use ".PropertiesAutowired(true)" all the time
var builder = new ContainerBuilder();
builder.RegisterType<Logger>()
.PropertiesAutowired(true)
.SingleInstance();
This can be done with a module, e.g.
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>();
I think you might be misunderstanding the true
paramerter to PropertiesAutowired
- it determines how circular dependencies are supported and should probably remain false
. To emulate the true
setting you can attach to Activated
instead of Activating
above.
However, if at all possible, use constructor injection even for "optional" dependencies like your ILog
. It leads to cleaner components (e.g. fields can be made readonly
) and dependencies are more understandable (they're all in the constructor, and there's no guessing about the meaning of individual properties.)
Only consider using property injection when there are multiple configurations of the application and in some configurations the dependency will be truly absent.
Even in these cases, the "Null Object" pattern is usually a better fit.
这篇关于设置AutoFac使用PropertiesAutowired(真)作为默认?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!