开发者

Managing dependencies

开发者 https://www.devze.com 2023-03-09 13:19 出处:网络
If you use mocks to test object interactions, you\'ll have to pass collaborators via constructors or specific methods. In a sufficiently complex application you\'ll have a lot of small objects interac

If you use mocks to test object interactions, you'll have to pass collaborators via constructors or specific methods. In a sufficiently complex application you'll have a lot of small objects interacting with each other. How do you manage the construction of the whole object graph at the topmost level of an app? In short, how do you deal with the following:

// arbitrarily complex
A a = new A(new B(new C(new D(new ...)), new E(new ...)), new F(new G(new ...)));
a.doSomething(开发者_运维百科);

It seems that dependency injection containers are the best solution in such cases. Are there any other good strategies to simplify dependency management?


The example given is simply Poor Man's DI. As long as you constrain yourself to composing the entire object graph in the application's Composition Root (entry point) you'd be doing fine. (As an aside, I recently heard Dan North refer to this as 'new' is the new 'new' - alluding to people in the Java community are beginning to move back to this way of constructing object graphs instead of using containers).

However, you can definitely use a DI Container as well, as long as you follow the Register Resolve Release pattern. Particularly in request-based applications (web apps and services) managing lifetime can be complex with Poor Man's DI, so in those types of apps, a container can be very helpful.


As far as I know, the only way to keep all these dependencies under control is to either create a general Context object that you can pass around (but even that has its complexities), or to use IoC with constructor injection.

Especially in the example you give, CI is a good solution because you can manage the complexities simply by configuring the container.

Just my 2 cents...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号