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

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

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

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

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

不断增加的参数列表。由于集装箱是我的依赖注入容器,为什么我不能只是这样做:

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.

一个构造器注入的美妙的好处是,它使违反单一职责原则昭然若揭。

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

当发生这种情况,它的时间来重构到门面服务。总之,建立一个新的,更加粗粒度界面,隐藏的部分或全部,你目前需要细粒度的依赖之间的互动。

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

发布评论

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

>www.elefans.com

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