C# 如何初始化通过构造函数注入的服务

问题描述 投票:0回答:1
当我使用依赖注入时,我试图理解我会如何:

    通过调用特定的构造函数来实例化注入?
  1. 如果我需要用 2 个不同的构造函数初始化这两个单独的实例怎么办?
  2. 是否可以在应用程序的类构造函数之外实例化注入的类?
我不确定这是否是 DI 的适当使用,但我只是想了解我是否遗漏了一些东西。考虑下面这个例子。为了清楚起见,我在评论中标记了问题。如果您对如何以最合适的方式实现其中任何一个有建议,我很欣赏您的见解。

假设我的服务定义如下:

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(); } }
    
c# dependency-injection factory
1个回答
0
投票
“初始化”类与依赖注入是对立的,因为理论上你不知道提供给你的对象是否是其他对象正在使用的同一个对象。

根据您真正想要完成的任务,不同的工具可能会有所帮助。例如:

  • Keyed Services 为您的每个依赖项提供不同的实例。
  • 通用类型:注入
  • IMyClass<MyType1>
     和/或 
    IMyClass<MyType2>
  • 使用依赖注入来解析某些
  • MyClass
     的依赖项的工厂类,但允许您提供仅在运行时已知的值作为 
    Create()
     方法的参数。
  • 放弃 DI,只在需要时创建一个
  • new()
     实例。
© www.soinside.com 2019 - 2024. All rights reserved.