依赖注入-正确使用接口? [英] Dependency Injection - Proper use of interfaces?

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

问题描述

我一直在阅读有关DI和最佳做法的信息,但仍未找到该问题的答案。

I've been reading about DI and best practices, and still haven't found the answer to this question. When should I use interfaces?


  1. 某些开发人员建议为每个要注入的对象添加接口。这将构成一个模块化的应用程序。

  2. 其他一些反对者。

所以我的问题是哪个是正确的?

So my question is which one is correct?

编辑:

下面是双方,我仍然看不到使用接口的优势。在这两种情况下,我都可以轻松模拟类并更改实现

Below are the two sides, I still don't see the advantage of using interfaces. In both cases I can easily mock classes, and change the implementations

使用接口

bind(IUserStorage.class).to(UserStorage.class);
// Unit test
bind(IUserStorage.class).to(Mock(UserStorage.class));

不使用界面

bind(UserStorage.class).to(UserStorage.class);
// Unit test
bind(UserStorage.class).to(Mock(UserStorage.class));


推荐答案

我不相信使用接口也是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.

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

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