且构网

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

依赖注入-正确使用接口?

更新时间:2023-01-11 09:56:11

我不相信使用接口也是OOP原则!

I can't believe using interfaces is againt OOP principles!

在这种情况下,我肯定会使用接口。这意味着您可以轻松地耦合组件,并且可以轻松进行模拟和/或替代。许多DI框架将使用这些接口来提供其他功能(例如,创建映射到真实对象的代理对象,但具有其他功能)。

I would definitely use interfaces in this scenario. It means you're loosely coupling your components and can easy mock and/or substitute alternatives. Lots of DI frameworks will use the interfaces in order to provide additional functionality (e.g. create proxy objects mapped to the real objects, but with additional features).

尝试对除最简单的注入对象以外的所有对象使用接口。在某些阶段,您将要利用可替换性,框架代码生成等,而改型接口的使用是另外一个难题,在项目开始时就很容易避免。

As such I would try and use interfaces for all but the most trivial of injected objects. At some stage you're going to want to make use of substitutability, framework code generation etc. and retrofitting interface usage is an additional pain that it's easy to avoid at the beginning of a project.