【问题标题】:Set AutoFac to use PropertiesAutowired(true) as default?将 AutoFac 设置为默认使用 PropertiesAutowired(true)?
【发布时间】:2010-08-02 03:30:27
【问题描述】:

有没有办法可以将 AutoFac 设置为使用 PropertiesAutowired(true) 作为所有注册类型的默认值。

即我不想一直使用“.PropertiesAutowired(true)”

var builder = new ContainerBuilder();
builder.RegisterType<Logger>()
    .PropertiesAutowired(true)
    .SingleInstance();

【问题讨论】:

    标签: .net dependency-injection ioc-container


    【解决方案1】:

    这可以通过一个模块来完成,例如

    class InjectPropertiesByDefaultModule : Autofac.Module {
        protected override void AttachToComponentRegistration(
            IComponentRegistration registration,
            IComponentRegistry registry) {
                registration.Activating += (s, e) => {
                    e.Context.InjectProperties(e.Instance);
                };
        }
    }
    

    然后:

    builder.RegisterModule<InjectPropertiesByDefaultModule>();
    

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

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

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

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

    【讨论】:

    • 另外 - 如果您正在集成 Log4Net,请查看:code.google.com/p/autofac/wiki/Log4NetIntegration :)
    • 谢谢西蒙 - 应该是“注册” - 现在修复了。
    • Doh,不错,我们不应该低估 Autofac 模块的力量 :) 我无知的答案特此修改。
    【解决方案2】:

    不,没有。但是,如果您批量注册类型或按照惯例注册类型会更容易,例如使用builder.RegisterAssemblyTypes(..)

    更新:有,见@Nicholas answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-17
      • 2014-02-04
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2016-04-25
      相关资源
      最近更新 更多