0

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. i.e. 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,

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

The solution is the use the name of the parameter declared in constructer and not the actual type, as such:

IParent parent = Container.Resolve<IParent>(parent, new ParameterOverride("doc", doc));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.