我们需要依赖注入的接口吗? [英] Do we need interfaces for dependency injection?

查看:32
本文介绍了我们需要依赖注入的接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Core 应用程序.该应用程序几乎没有可以完成某些工作的帮助程序类.每个类都有不同的签名方法.我在网上看到很多 .net 核心示例,它们为每个类创建接口,然后使用 DI 框架注册类型.例如

I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

 public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }

基本上每个接口只有一个类.然后我将这些类型注册为 DI 为

Basically for each interface there is only one class. Then i register these types with DI as

 services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();

但是我可以在没有接口的情况下注册类型,所以这里的接口看起来是多余的.例如

But i can register type without having interfaces so interfaces here look redundant. eg

 services.AddScoped<Storage>();
 services.AddScoped<Ocr>();

那么我真的需要接口吗?

So do i really need interfaces?

推荐答案

不,您不需要需要依赖注入的接口.但是依赖注入对它们更有用!

No, you don't need interfaces for dependency injection. But dependency injection is much more useful with them!

如您所见,您可以向服务集合注册具体类型,ASP.NET Core 会将它们毫无问题地注入到您的类中.注入它们而不是简单地使用 new Storage() 创建实例的好处是 服务生命周期管理(瞬态 vs. 范围 vs. 单例).

As you noticed, you can register concrete types with the service collection and ASP.NET Core will inject them into your classes without problems. The benefit you get by injecting them over simply creating instances with new Storage() is service lifetime management (transient vs. scoped vs. singleton).

这很有用,但只是使用 DI 的部分功能.正如@DavidG 指出的那样,接口如此频繁地与 DI 配对的一个重要原因是因为测试.让您的消费者类依赖于接口(抽象)而不是其他具体的类,这会使它们更容易测试.

That's useful, but only part of the power of using DI. As @DavidG pointed out, the big reason why interfaces are so often paired with DI is because of testing. Making your consumer classes depend on interfaces (abstractions) instead of other concrete classes makes them much easier to test.

例如,您可以创建一个 MockStorage 来实现 IStorage 以在测试期间使用,而您的使用者类应该无法区分.或者,您可以使用模拟框架轻松地动态创建模拟的 IStorage.用具体的类做同样的事情要困难得多.接口使得在不改变抽象的情况下很容易替换实现.

For example, you could create a MockStorage that implements IStorage for use during testing, and your consumer class shouldn't be able to tell the difference. Or, you can use a mocking framework to easily create a mocked IStorage on the fly. Doing the same thing with concrete classes is much harder. Interfaces make it easy to replace implementations without changing the abstraction.

这篇关于我们需要依赖注入的接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆