When i use dependency injection, i am trying to understand how woudl i:
- instantiate the injected by calling specific constructor?
- What if i needed to initialize this two separate instances with 2 different constructors?
- 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();
}
}