tau
tau

Reputation: 6749

Instantiate dependency injected class

Is there any way to get an instance of a class from the dependency injector?

For example, I register my types and then have a class like this:

public class A {
    private readonly Iinterface _object;

    public A (Iinterface object) {
        _object = object;
    }

    //do stuff using _object
}

public class B {
    public void DoSomething() {
        var instanceOfA = DIContainer.GetInstance(typeof(A));
        //do stuff with instanceOfA which has been constructed using DI
    }
}

Currently, I would have to register class A to be injected, and then have that injected into class Bs constructor. I'm just curious if there is a way to get an instance of A created for me from Unity with the depedencies injected automatically so I don't have to register it or pass through objects.

Please keep in mind that is not an actual use case I am considering, but I want to learn more about my options with dependency injection and Unity specifically.

Upvotes: 0

Views: 2812

Answers (2)

TTat
TTat

Reputation: 1496

In Unity, there are a few ways to get dependencies.

  1. Constructor Injection
  2. Property Injection
  3. Manually resolve

I believe what you're asking for is #3.

In your example, you can get a class A instance (granted you've already registered Iinterface) by:

unityContainer.Resolve<A>();

A simplified way to think of Unity is it's a really smart Factory that can give you an object in the Constructor, Property, or by calling a Method. Ask for any object type or interface type, and it will give you one. The caveat is you need to give it clues on how to handle ambiguities. That's basically where the registrations come into play.

In your example above, the only ambiguity is Iinterface so that's the only class that you will need to register. Resolving class A or B doesn't need any registrations because it's already a concrete type.

Upvotes: 4

D Stanley
D Stanley

Reputation: 152521

It depends on the relationship between A and B:

If B depends on A, then it would make sense for A to inject the dependency into B (or perhaps to inject A itself).

I would not advise allowing B to "find" the dependency by looking at A. At best you have a strong dependency between B and A, at worst you end up with a "Service Locator" anti-pattern.

Unless you have a critical need to keep the dependency the same between A and B I would not couple them any more than you have to.

Upvotes: 1

Related Questions