.net - 将 AutoFac 设置为默认使用 PropertiesAutowired(true)?

标签 .net dependency-injection ioc-container

有没有办法可以将 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>();

我认为您可能误解了 PropertiesAutowiredtrue 参数 - 它决定了如何支持循环依赖,并且可能应该保持 false。要模拟 true 设置,您可以附加到 Activated 而不是上面的 Activating

但是,如果可能的话,即使对于像 ILog 这样的“可选”依赖项,也要使用构造函数注入(inject)。它导致组件更简洁(例如,可以将字段设置为 readonly)并且依赖项更易于理解(它们都在构造函数中,并且无需猜测各个属性的含义。)

仅当应用程序有多个配置时才考虑使用属性注入(inject),并且在某些配置中确实不存在依赖项。

即使在这些情况下,“Null Object”模式通常更适合。

关于.net - 将 AutoFac 设置为默认使用 PropertiesAutowired(true)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3384812/

相关文章:

c# - 使用 .net 或 C# 为 iOS 发送通知

c# - 如何增加 OrmLite ServiceStack 中的命令超时?

c# - 你在 C# 中使用 "this"运算符吗?

c# - 使用 CaSTLe Windsor 在基类中注入(inject)原始属性

c# - Autofac - 如何在创建实例时获取类名

spring - 多个同时访问 Spring Singleton 实例时

c# - 帮我找到一个适用于 asp.net 应用程序的最小摩擦日志记录解决方案

android - 使用 Dagger-2 和 Autofactory 时实现辅助注入(inject)的问题

c# - 自定义成员(member)提供者 : No parameterless constructor defined for this object

spring - 未定义名为 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' 的 bean