gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:09 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com