依赖注入容器与注册表模式 [英] Dependency Injection Container vs Registry pattern

查看:98
本文介绍了依赖注入容器与注册表模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道依赖注入原理是关于去耦代码。而不是在类中创建新的实例,而是注入它们,这使得它们
松散耦合。



现在,如果我有在我的应用程序中传递一组通过几个类使用的对象,我可以创建一个容器(通常称为依赖注入容器)。



我在做,因为我必须传递一个配置对象,一个记录器对象,一个翻译器对象等,将通过我的应用程序的几个类实例使用。我将整个容器通过几个类,即使不是所有的类都需要访问容器内的所有对象。这引起了以下问题:如果我创建一个全局注册表并将对象放在那里,然后检索它们像Registry :: getInstance() - > get('logger'),那么有什么区别? ? Wether我使用全局注册表或依赖项容器,类isntances将访问容器或注册表中的所有对象,即使他们不需要查看/访问所有这些对象。



结论:如果我沿着我的类或全局注册表传递依赖注入容器,有什么区别?

解决方案

p>我认为这里缺少的一点是 CompositionRoot 。根据DI原则一次您可以在组合根中定义绑定,然后在整个应用程序中使用引用。这就是DI Container带来的价值。



根据定义组合根是组合在一起的应用程序中的(最好是)唯一的位置。



我将添加一个组合根,也是一个独特的位置,所有重要的决定关于你的应用程序行为发生。这是什么对象在什么情况下使用。这是OO系统的核心,其中对象之间的交互提供了系统的行为。


I understand that the Dependency Injection principle is all about decoupling code. Instead of making new instances in the classes, instead you inject them, which make them loosely coupled.

Now if I have to pass on a set of objects that will be used through several classes throughout my application, I can make a container (commonly called dependency injection container).

That is exactly what i am doing because I have to pass a config object, a logger object, a translator object, etc. which will be used through several classes instances of my application. I am passing the whole container through several classes, even if not all of the classes need access to all the objects within the container. This led me to the following question: what is the difference if I create a global Registry and put the objects in there, then retrieve them like Registry::getInstance()->get('logger'); ? Wether I use a global registry or a dependency container, class isntances will have access to all the objects within the container or registry, even if they don't need to see/access all of them.

Conclusion: What is the difference if I pass a dependency injection container along my classes or a global Registry ?

解决方案

I think the point missing here is CompositionRoot .As per DI Principle once you define your bindings in the Composition Root , then you can use the reference throughout the application. That is the value DI Container brings.

As per definition "A Composition Root is a (preferably) unique location in an application where modules are composed together."

I will add that a Composition Root also a unique location where all important decisions about your applications behavior takes place. That is what object to use in what situation.This is the heart of a OO system where interaction between the objects deliver the behavior of the system.

这篇关于依赖注入容器与注册表模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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