依赖注入必须以牺牲封装为代价吗? [英] Must Dependency Injection come at the expense of Encapsulation?

查看:23
本文介绍了依赖注入必须以牺牲封装为代价吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确,依赖注入的典型机制是通过类的构造函数或类的公共属性(成员)注入.

If I understand correctly, the typical mechanism for Dependency Injection is to inject either through a class' constructor or through a public property (member) of the class.

这暴露了被注入的依赖,违反了 OOP 封装原则.

This exposes the dependency being injected and violates the OOP principle of encapsulation.

我确定这种权衡是否正确?你如何处理这个问题?

Am I correct in identifying this tradeoff? How do you deal with this issue?

另请参阅下面我对自己问题的回答.

推荐答案

您可能会发现另一种看待这个问题的方式.

There is another way of looking at this issue that you might find interesting.

当我们使用 IoC/依赖项注入时,我们没有使用 OOP 概念.诚然,我们使用面向对象的语言作为宿主",但 IoC 背后的思想来自面向组件的软件工程,而不是面向对象.

When we use IoC/dependency injection, we're not using OOP concepts. Admittedly we're using an OO language as the 'host', but the ideas behind IoC come from component-oriented software engineering, not OO.

组件软件都是关于管理依赖关系的——一个常用的例子是 .NET 的组装机制.每个程序集都会发布它引用的程序集列表,这使得整合(并验证)正在运行的应用程序所需的部分变得更加容易.

Component software is all about managing dependencies - an example in common use is .NET's Assembly mechanism. Each assembly publishes the list of assemblies that it references, and this makes it much easier to pull together (and validate) the pieces needed for a running application.

通过 IoC 在我们的 OO 程序中应用类似的技术,我们的目标是使程序更易于配置和维护.发布依赖项(作为构造函数参数或其他)是其中的关键部分.封装并不真正适用,因为在面向组件/服务的世界中,没有可以泄漏细节的实现类型".

By applying similar techniques in our OO programs via IoC, we aim to make programs easier to configure and maintain. Publishing dependencies (as constructor parameters or whatever) is a key part of this. Encapsulation doesn't really apply, as in the component/service oriented world, there is no 'implementation type' for details to leak from.

不幸的是,我们的语言目前没有将细粒度的、面向对象的概念与粗粒度的面向组件的概念分开,所以这是一个你必须记住的区别:)

Unfortunately our languages don't currently segregate the fine-grained, object-oriented concepts from the coarser-grained component-oriented ones, so this is a distinction that you have to hold in your mind only :)

这篇关于依赖注入必须以牺牲封装为代价吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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