使用AutoFac手动调用属性注入 [英] manually invoke property injection with AutoFac

查看:475
本文介绍了使用AutoFac手动调用属性注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设所有依赖项都已在程序开始时注册.在程序的后面,如何使用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?

推荐答案

您可以使用PropertiesAutowired在容器中注册对象,然后在需要安装实例时使用resolve:

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

或者如果您不想在容器中注册,则可以在现有实例上使用InjectProperties方法:

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

这篇关于使用AutoFac手动调用属性注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆