AutoFac文檔
目錄
- 開始
- Registering components
- 控制范圍和生命周期
- 用模塊結構化Autofac
- xml配置
- 與.net集成
- 深入理解Autofac
- 指導
- 關於
- 詞匯表
屬性注入
屬性注入使用可寫屬性而不是構造函數參數實現注入。
介紹
如果component是一個委托,使用一個對象初始化:
builder.Register(c => new A { B = c.Resolve<B>() });
為了提供循環依賴(就是當A使用B的時候B已經初始化),需要使用OnActivated事件接口:
builder.Register(c => new A()).OnActivated(e => e.Instance.B = e.Context.Resolve<B>());
通過發射,使用PropertiesAutowired()修飾符注入屬性。
builder.RegisterType<A>().PropertiesAutowired();
如果你預先知道屬性的名字和值,你可以使用
builder.WithProperty("propertyName", propertyValue)。