Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manually invoke property injection with AutoFac

Tags:

autofac

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?

like image 556
JoelFan Avatar asked Feb 19 '23 12:02

JoelFan


1 Answers

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
like image 70
nemesv Avatar answered Mar 05 '23 22:03

nemesv