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

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

问题描述

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

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概念。诚然,我们使用OO语言作为主机,但是IoC背后的想法来自面向组件的软件工程,而不是OO。

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天全站免登陆