c# - 有没有更好的方法来使用依赖注入(inject)来实例化接口(interface)?

标签 c# .net dependency-injection

我发现自己做了很多这样的事情;

IService service1;
IService service2;

SomeController(IService1 service1, IService2 service2)
{
    this.service1 = service1;
    this.service2 = service2;
}

除了像这样注入(inject)和实例化接口(interface)还有什么替代方法?它开始让人觉得多余 - 但是,我是一个菜鸟,还不太清楚为什么或如何。

最佳答案

C#中有四种DI

  • Constructor Injection
  • Setter or property Injection
  • Method Injection
  • Service Locator Injection

您已经使用了构造函数注入(inject),这是最常用的方法,其他替代方案不一定更好,但您可以选择更方便的方式,你可以在这里找到每一个的例子:https://www.c-sharpcorner.com/article/understanding-the-dependency-injection-using-constructor-property-and-method-in/

您还可以找到关于何时使用属性依赖注入(inject)而不是构造函数注入(inject)以及反之亦然的解释? here :

The Constructor Dependency Injection in C# is the standard for dependency injection. It ensures that all the dependency objects are initialized before we are going to invoke any methods or properties of the dependency object, as a result, it avoids the null reference exceptions.

The Setter/Property Dependency Injection in C# is rarely used in real-time applications. For example, if I have a class which has several methods but those methods does not depend on any other objects. Now I need to create a new method within the same class but that new method now depends on another object. If we use the constructor dependency injection here, then we need to change all the existing constructor calls where we created this class object. This can be a very difficult task if the project is a big one. Hence, in such scenarios, the Setter or Property Dependency Injection can be a good choice.

关于c# - 有没有更好的方法来使用依赖注入(inject)来实例化接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300542/

相关文章:

c# - Microsoft.SqlServer.Types.dll——为什么/如何在我的解决方案中引用它?

.net - 从 DispatcherObject 继承

perl - Moose 类的依赖注入(inject)

c# - Image.FromFile() 或 FromStream() 在 GdiplusStartup 上挂起

c# - .NET 是否有一个简单的 "virtual file"类(如果源代码可用,则为 c#)?

dependency-injection - 无状态 EJB 未注入(inject)消息驱动 bean (MDB)

android - Koin vs Kodein - 依赖注入(inject)你更喜欢什么? Kotlin

c# - 如何在 C# 中声明位变量并为其设置值?

c# - 具有 C# DateTime 偏移量的 Excel 日期时间

c# - 带OUT参数的WebMethod,然后在javascript中调用方法