如何避免依赖注入构造函数的疯狂?

编程入门 行业动态 更新时间:2024-10-21 17:37:23
本文介绍了如何避免依赖注入构造函数的疯狂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现我的构造函数开始看起来像这样:

I find that my constructors are starting to look like this:

public MyClass(Container con, SomeClass1 obj1, SomeClass2, obj2.... )

随着参数列表的不断增加.既然Container"是我的依赖注入容器,为什么我不能这样做:

with ever increasing parameter list. Since "Container" is my dependency injection container, why can't I just do this:

public MyClass(Container con)

每个班级?有什么缺点?如果我这样做,感觉就像我在使用美化的静态.请分享您对 IoC 和依赖注入疯狂的看法.

for every class? What are the downsides? If I do this, it feels like I'm using a glorified static. Please share your thoughts on IoC and Dependency Injection madness.

推荐答案

如果您将容器用作服务定位器,它或多或少是一个美化的静态工厂,这是对的.出于很多原因我认为这是一种反模式(另见此摘录 来自我的书中).

You are right that if you use the container as a Service Locator, it's more or less a glorified static factory. For lots of reasons I consider this an anti-pattern (also see this excerpt from my book).

构造函数注入的一大好处是它违反了单一职责原则很明显.

One of the wonderful benefits of Constructor Injection is that it makes violations of the Single Responsibility Principle glaringly obvious.

发生这种情况时,是时候重构为 Facade Services.简而言之,创建一个新的、更粗粒度的界面,隐藏您当前需要的部分或全部细粒度依赖项之间的交互.

When that happens, it's time to refactor to Facade Services. In short, create a new, more coarse-grained interface that hides the interaction between some or all of the fine-grained dependencies you currently require.

更多推荐

如何避免依赖注入构造函数的疯狂?

本文发布于:2023-11-16 11:46:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   疯狂

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!