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

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

问题描述

我有一个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()创建实例来注入它们所获得的好处是服务寿命管理(瞬态,作用域与单例)。

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.

例如,您可以创建一个实现了 IStorage 的MockStorage 可以在测试期间使用,而您的使用者类应该无法分辨出两者之间的区别。或者,您可以使用模拟框架轻松地动态创建模拟的 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天全站免登陆