When i use dependency injection, i am trying to understand how woudl i:
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();
}
}
"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:
IMyClass<MyType1>
and/or IMyClass<MyType2>
.MyClass
's dependencies, but allow you to provide values known only at runtime as arguments to a Create()
method.new()
instance when you need it.