How to avoid Dependency Injection constructor madness?
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)
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.
I don't think your class constructors should have a reference to your IOC container period. This represents an unnecessary dependency between your class and the container (the type of dependency IOC is trying to avoid!).
The difficulty of passing in the parameters is not the problem. The problem is that your class is doing too much, and should be broken down more.
Dependency Injection can act as an early warning for classes getting too big, specifically because of the increasing pain of passing in all of the dependencies.
链接地址: http://www.djcxy.com/p/77784.html上一篇: 与SOLID和Dependecy Injection混淆
下一篇: 如何避免依赖注入构造函数疯狂?