假设我的服务定义如下:
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(){...}
}
我可以在我的应用程序中使用它,如下所示:
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();
}
}
根据您真正想要完成的任务,不同的工具可能会有所帮助。例如:
IMyClass<MyType1>
和/或
IMyClass<MyType2>
。
MyClass
的依赖项的工厂类,但允许您提供仅在运行时已知的值作为
Create()
方法的参数。
new()
实例。