2012-11-15 83 views
2

假設所有依賴項已經在程序開始時被註冊。在程序的後面幾點你如何使用AutoFac創建一個帶有無參數構造函數的新對象,並將註冊的屬性注入到對象中?使用AutoFac手動調用屬性注入

回答

6

您可以用PropertiesAutowired容器註冊您的對象,然後,當你需要一個instace使用解析:

ContainerBuilder builder = new ContainerBuilder(); 
// builder register other dependencies 
builder.RegisterType<MyObject>().PropertiesAutowired(); 

var container = builder.Build(); 

var myObject = container.Resolve<MyObject>(); //the properties will be filled 

或者,如果你不想在容器中註冊您可以使用上的InjectProperties方法現有實例:

ContainerBuilder builder = new ContainerBuilder(); 
// builder register other dependencies 

var container = builder.Build(); 

var myObject = new MyObject(); 
container.InjectProperties(myObject); //the properties will be filled