简体   繁体   中英

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:

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. ie it seems like a new Document(), and not the actual doc that I'm passing in when calling Resolve.

My question is how do I pass in an instance of doc to resolve a concrete type of IParent?

Cheers,

You should register Parent1 with dependency to Document in constructor:

    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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM