且构网

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

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

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

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

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.