2010-08-02 191 views
3

有沒有一種方法可以將AutoFac設置爲使用PropertiesAutowired(true)作爲所有正在註冊的類型的默認值。設置AutoFac默認使用PropertiesAutowired(true)?

即我不想用 「.PropertiesAutowired(真)」 的所有時間

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

回答

9

這可以用模塊來完成,例如,

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

然後:

builder.RegisterModule<InjectPropertiesByDefaultModule>(); 

我想你可能會誤解true paramerter到PropertiesAutowired - 它決定如何依賴圓形的支持,並應可能保持false。要模擬true設置,您可以將其附加到Activated而不是上面的Activating

但是,如果可能的話,即使對於「可選」依賴項(如ILog)也要使用構造函數注入。它導致更清潔的組件(例如,字段可以被製造爲readonly)並且依賴關係更易於理解(它們都在構造器中,並且沒有關於單獨屬性的含義的猜測)。

只有在存在時才考慮使用屬性注入是應用程序的多種配置,並且在某些配置中,依賴關係將確實不存在。

即使在這些情況下,「空對象」模式通常更合適。

+0

另外 - 如果你正在整合Log4Net,請看看:http://code.google.com/p/autofac/wiki/Log4NetIntegration :) – 2010-08-02 22:50:20

+0

Nic。在你的代碼中,「e」來自哪裏? – Simon 2010-08-03 02:38:29

+0

謝謝西蒙 - 應該是「註冊」 - 現在已經修復。 – 2010-08-03 05:59:50

0

沒有,沒有。雖然,如果你批量註冊類型或按照慣例註冊類型,它會更容易,例如,使用builder.RegisterAssemblyTypes(..)

更新:是的,有,請參閱@Nicholas answer

+0

正如我所料。謝謝 – Simon 2010-08-02 12:35:48