我发现我的构造函数开始看起来像这样:
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.
更多推荐
如何避免依赖注入构造函数的疯狂?
发布评论