Sim*_*mon 3 .net dependency-injection ioc-container
有没有办法我可以设置AutoFac使用PropertiesAutowired(true)作为所有注册类型的默认值.
即我不想一直使用".PropertiesAutowired(true)"
var builder = new ContainerBuilder();
builder.RegisterType<Logger>()
.PropertiesAutowired(true)
.SingleInstance();
Run Code Online (Sandbox Code Playgroud)
这可以通过模块完成,例如
class InjectPropertiesByDefaultModule : Autofac.Module {
protected override void AttachToComponentRegistration(
IComponentRegistration registration,
IComponentRegistry registry) {
registration.Activating += (s, e) => {
e.Context.InjectProperties(e.Instance);
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
builder.RegisterModule<InjectPropertiesByDefaultModule>();
Run Code Online (Sandbox Code Playgroud)
我认为你可能误解了true参数PropertiesAutowired- 它决定了循环依赖的支持方式,应该保留false.要模拟true您可以附加到上面Activated而不是Activating上面的设置.
但是,如果可能的话,使用构造函数注入,即使是像"你的"这样的"可选"依赖项ILog.它导致更清晰的组件(例如可以创建字段readonly),并且依赖性更容易理解(它们都在构造函数中,并且没有猜测单个属性的含义.)
只有在应用程序有多个配置时才考虑使用属性注入,在某些配置中,依赖关系将完全不存在.
即使在这些情况下,"空对象"模式通常也更合适.
| 归档时间: |
|
| 查看次数: |
1705 次 |
| 最近记录: |