使用 Microsoft Unity IOC,如何将现有对象传递给它来注入?
所以如果我有:
public class CustomerViewModel
{
public CustomerViewModel(ICustomer customer)
{
this.customer = customer
}
}
那么有没有办法实现:
ICustomerViewModel customerViewModel = container.Resolve<ICustomerViewModel>(existingCustomer);
So if I have:
public class CustomerViewModel
{
public CustomerViewModel(ICustomer customer)
{
this.customer = customer
}
}
then is there a way to achieve:
ICustomerViewModel customerViewModel = container.Resolve<ICustomerViewModel>(existingCustomer);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你想通过属性和方法注入来构建一个现有的实例,你可以使用以下方法:
一般来说我不建议使用Unity的这个功能。有时您需要它,但它通常是一个警告信号,可以通过稍微调整设计来修复,以便更自然地使用 IoC 作为模式(而不是框架)。有了有关如何使用它的更多详细信息,SO 社区可能可以提供一些其他选项......
If you want to build-up an existing instance through property and method injection, you can use the following:
In general I would not recommend using this feature of Unity. Sometimes you need it, but it's usually a warning sign that could be fixed by adjusting the design a bit to work more naturally with IoC as a pattern (not a framework). With more details on how you are using it, the SO community can probably offer some other options...
由于依赖项注入容器旨在提供完成的对象,因此您需要使用工厂模式(在这些情况下很常见)来实现所需的配置:
Since the dependency injection container is designed to provide finished objects, you'll need to use a factory pattern (which is quite common in these cases) to achieve your desired configuration:
检查“我可以将构造函数参数传递给 Unity 的 Resolve() 方法吗?' 问题(也在 Stack Overflow 上)。
Check the 'Can I pass constructor parameters to Unity's Resolve() method?' question (also on Stack Overflow).