且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们需要依赖注入接口吗?

更新时间:2023-01-11 10:05:17

否,您不需要不需要接口进行依赖项注入。但是依赖注入对它们更有用!

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.