开发者

how to understand the rule: IoC container should be explicitly used only in Bootstrapper?

Am I right in understanding that 1) Ideally, resolve method should be called only once and build whole application graph at one bout. 2) Library's classes should be ready for IoC tool (publish all dependencies) but should not use "secretly" any IoC containers ; so the situations where we create container on any other layers except "bootsrapper" should be avoided. 3) Send of IContainer to subclusses for additional "resolvings" is also abortive decision.

Those principles are very logical for me, I share them. But I still have doubts in answering on this question: "why there are still used such concepts like.."

1) transient life-time - since we build infrastructure 开发者_如何学运维on start-up all objects should live "application life-time" and generally should be singletons; if we need to create some "per call" objects then with IoC we resolve only theirs abstract factories, which should create "per call" infrastructure objects (avoiding "nested" containers, and "transient" container's instances); 2) subcontainers, parent/child containers; 3) "hierarchy life time".

Now I explain for my self that those concepts exists as solutions for "no ideal world", but may be I miss something?


Even if you only resolve a single object graph (which would be the case e.g. in a desktop application), Transient is still different from Singleton because you might have an abstraction which is used by multiple consumers (e.g. an ILog interface). If the lifetime is Transient, each consumer will get its own instance, but if the lifetime is Singleton, all consumers will share the same instance.

Sharing an instance is often preferable because it uses less resources, but may have issues with thread-safety etc. so you always need to consider the tradeoffs.

This whole discussion is just enlarged when you consider request-based applications, such as web sites or services. For such applications, Singletons can be shared across many different requests, but must be thread-safe, whereas Transient objects are safer, but less efficient.

Some containers have a per web request lifestyle to provide a middle-of-the-road solution for those cases, but those that don't often have a Hierarchical or context-based lifestyle which can be used to address the same scenario, since you can create a container scope per HTTP request.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜