Search code examples
c#dependency-injectionfactory

C# How to initialize service that was injected via constructor


When i use dependency injection, i am trying to understand how woudl i:

  1. instantiate the injected by calling specific constructor?
  2. What if i needed to initialize this two separate instances with 2 different constructors?
  3. Is it at all possible to instantiate injected class outside of the application's class constructor?

I am not sure if this is even appropriate use of DI, but i just want to understand if I am missing something. Consider this example below. I marked questions in the comments, for clarity. If you have a suggestion on how to achieve any of this in most appropriate way, id appreciate the insight.

Lets say i have my service defined like this:

public interface IMyClass
{
    void DoStuff();
}

public class MyClass: IMyClass
{
    public MyClass(MyType1 t1){//do somethign with t1 in conctructor}
    public MyClass(MyType2 t2){//do somethign with t2 in conctructor}
    public void DoStuff(){...}
}

I can use it in my application like so:

public class MyProgram
{
    private IMyClass _myClass1;
    ptivate IMyClass _myClass2;
    
    public MyProgram(IMyClass myClass)
    {
        MyType1 type1 = GetMyType1();
        MyType2 type2 = GetMyType2();
        _myClass1 = myClass; //Question 1. I am looking for a way to initialize _MyClass with type1
        _myClass2 = myClass; //Question 2. I am looking for a way to initialize _MyClass with type2
    }
    
    public void MyMethod1()
    {
        //Question 3. can _myClass1 be instantiated here with type1?
        _myClass1.DoStuff();
    }
    
    public void MyMethod2()
    {
        //Question 3. can _myClass2 be instantiated here with type2?
        _myClass2.DoStuff();
    }
}

Solution

  • "Initializing" classes is kind of antithetical to Dependency Injection, because in theory you don't know whether the object provided to you is the same object being used by other objects.

    Depending on what you're really trying to accomplish, different tools might be able to help. For example:

    • Keyed Services to give you different instances for each of your dependencies.
    • Generic types: inject IMyClass<MyType1> and/or IMyClass<MyType2>.
    • Factory classes that use Dependency Injection to resolve some of MyClass's dependencies, but allow you to provide values known only at runtime as arguments to a Create() method.
    • Abandoning DI and just creating a new() instance when you need it.