IoC 之上的抽象工厂模式? [英] Abstract factory pattern on top of IoC?

查看:38
本文介绍了IoC 之上的抽象工厂模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我决定在一个更大的项目中使用 IoC 原则.但是,我想弄清楚困扰我很久的事情.我得出的结论是 IoC 容器是一种架构模式,而不是设计模式.换句话说,任何类都不应该知道它的存在,容器本身应该在应用层使用来拼接所有组件.从本质上讲,它成为了一个选项,在精心设计的面向对象模型之上.话虽如此,如何在不将 IoC 容器撒在各处(无论它们是否被抽象)的情况下访问已解析的类型?我在这里看到的唯一选择是利用抽象工厂,它使用 IoC 容器来解析具体类型.这应该很容易换成一组标准工厂.这是一个好方法吗?这里有没有人用过它,它对你的效果如何?还有其他的吗?

I have decided to use IoC principles on a bigger project. However, i would like to get something straight that's been bothering me for a long time. The conclusion that i have come up with is that an IoC container is an architectural pattern, not a design pattern. In other words, no class should be aware of its presence and the container itself should be used at the application layer to stitch up all components. Essentially, it becomes an option, on top of a well designed object-oriented model. Having said that, how is it possible to access resolved types without sprinkling IoC containers all over the place (regardless of whether they are abstracted or not)? The only option i see here is to utilize abstract factories which use an IoC container to resolve concrete types. This should be easy enough to swap out for a set of standard factories. Is this a good approach? Has anyone on here used it and how well did it work for you? Is there anything else available?

谢谢!

推荐答案

如您所见,依赖注入 (DI) 本身只是模式和技术的集合.

As you have already figured out, Dependency Injection (DI) itself is only a collection of patterns and techniques.

在应用程序的根部,我们连接了所有必要的对象图.这个地方叫做Composition Root,我们可以使用DI Container来为我们做这个接线,或者我们可以手动做(Pure DI).

At the root of the application we wire up all necessary object graphs. This place is called the Composition Root, and we can use a DI Container to do this wiring for us, or we can do it manually (Pure DI).

关键是在您的应用程序中只有一个地方强烈引用了特定技术(您的 DI 容器).应用程序的其余部分完全不知道对象图是如何连接起来的 - 重要的是所有必需的依赖项都已正确注入(您可以将 Constructor InjectionNull Guards 保证确实如此).

The point is that there's only one place in your application where there's a strong reference to a particular piece of technology (your DI Container). The rest of the app is blissfully unaware of how the object graph was wired up - all that matters is that all required dependencies were correctly injected (and you can use Constructor Injection with Null Guards to guarantee that this is so).

Abstract Factory 模式对于 DI 来说是一个非常有用的模式.本质上,在以下情况下使用抽象工厂:

The Abstract Factory pattern is a very useful pattern when it comes to DI. In essence, use Abstract Factory when:

  • 您需要提供一个或多个仅在运行时才知道的参数,然后才能解决依赖关系.
  • 依赖项的生命周期在概念上比消费者的生命周期短.

此处提供示例和更多信息:

Examples and more information is available here:

这篇关于IoC 之上的抽象工厂模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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