问题
Suppose all the dependencies have already been registered at the beginning of the program. At later points in the program how can you use AutoFac to create a new object with a parameterless constructor and inject the registered properties into the object?
回答1:
You can register your object in the container with PropertiesAutowired
then use resolve when you need an 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
Or if you don't want to register in the container your can use the InjectProperties
method on an existing instance:
ContainerBuilder builder = new ContainerBuilder();
// builder register other dependencies
var container = builder.Build();
var myObject = new MyObject();
container.InjectProperties(myObject); //the properties will be filled
来源:https://stackoverflow.com/questions/13390637/manually-invoke-property-injection-with-autofac