manually invoke property injection with AutoFac

穿精又带淫゛_ 提交于 2019-12-10 16:19:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!