[英]Unity – Resolving objects by passing constructor parameter
I have the following code: 我有以下代码:
interface IParent
{ }
class Parent1 : IParent
{
public Parent1 (Document doc)
{
}
}
class Parent2 : IParent
{
public Parent2 (Document doc)
{
}
}
My unity container is configured as per below: 我的统一容器如下配置:
Container.RegisterType<IParent, Parent1>("Parent1");
Container.RegisterType<IParent, Parent2>("Parent2");
I'm trying to resolve an IParent object (of type Parent1 or Parent2) by passing in an instance of Document to its constructor: 我试图通过将Document的实例传递到其构造函数来解析IParent对象(Parent1或Parent2类型):
string parent = "Parent1";
IParent parent = Container.Resolve<IParent>(parent, new ParameterOverride("Document", doc));
This isn't working for me. 这对我不起作用。 Using the debugger to step into the above line I get into the constructor but the Document is empty.
使用调试器进入上面的行,我进入了构造函数,但是Document为空。 ie it seems like a new Document(), and not the actual doc that I'm passing in when calling Resolve.
即它看起来像一个新的Document(),而不是我在调用Resolve时传递的实际文档。
My question is how do I pass in an instance of doc to resolve a concrete type of IParent? 我的问题是如何传递doc实例来解析IParent的具体类型?
Cheers, 干杯,
You should register Parent1
with dependency to Document
in constructor: 您应该在构造函数中注册对
Document
具有依赖关系的Parent1
:
Container.RegisterType<IParent, Parent1>("Parent1", new InjectionConstructor(doc));
then you can resolve an instance of that class: 那么您可以解析该类的实例:
string parentClass = "Parent1";
IParent parent = Container.Resolve<IParent>(parentClass);
解决方案是使用构造器中声明的参数名称而不是实际类型,例如:
IParent parent = Container.Resolve<IParent>(parent, new ParameterOverride("doc", doc));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.