Monday, July 23, 2007

Service Container is the Best Thing Since Timesliced Bread

Ever been struggling with the ever-morphing parameter list?

Or perhaps you've been struggling with coupling issues?

The Service Container is your salvation!

It is basically a dictionary keyed by type, typically an interface type. Need to pass that ICrucialInterface down the call chain? Just stuff it in there.

Important to recognize is that only the creator of the Service Container usually has the ability to populate it. Once populated, read-only access is assumed. This is accomplished with appropriate interfaces. In .NET these are called IServiceProvider (read-only) and IServiceContainer (read-write).

Service containers may be chained together in parent/child linkage. The holder of a reference to a child container also gains access to all "higher" levels of linkage.

The biggest benefit here is that you are future-proof. If the universe of parameters changes, there are no messy signature refactorings to contend with. Package boundaries remain pristine.

This is the classic early-vs-late binding tradeoff.

"So where's the down side, since you said it's a tradeoff?"

Ok, busted. There is one minor one, but this can quickly be turned into an advantage.

The bummer here is since you are now loosely coupled to the universe, you must physically dig every last reference out of the container before use. This can be advantaged by changing mindset to a dynamic mode, where nothing is required, and the logic accounts for this (unlike WestWorld....)

Couldn't find a reference to the ICrucialInterface? Either degrade gracefully (i.e. use the INotSoCrucialInterface), or throw an exception.

The chaining of Service Containers into a hierarchy can alter the scope of what is visible to downstream call sites. At any point, a caller can add to the container chain and use it in calls.

No comments:

Disclaimer

Look, this is humor, so put away the flame-thrower! Just have a laugh and go on your merry way....