2009
12.09

Recently I was wondering how PRISM (Composite Application Guidance for WPF & Silverlight) achieved a magic trick with its dependency injection (DI) container.

I knew in PRISM you are free to swop in your own DI container, which is nice but I was wondering how you achieved the trick of having your container available within itself.

What do I mean?  Put simple being able to resolve your DI Container in any class within your application.

Example: Where ‘Foo’ is just a plain old class within the application.

public class Foo : IFoo
{
	public Bar SomeProp { get; set; }
 
	public Foo(IContainer container)
	{
		Bar = container.Resolve<ibar>();		
	}
}

So I asked Glenn Block (one of the main guys behind PRISM at Microsoft) on Twitter how this was achieved and he got back to me with some great material which I thought I would share:

  • How to resolve a DI Container in Unity from itself.
  • Why this is bad.
  • How to do it but limiting the badness.

Note: Remember to read these ‘Blocks’ of tweets backwards as it is Twitter. So with 1 & 3 start at the bottom and read up.

0 – Me:

 image

1 – GBlock:

 image

(START FROM THE BOTTOM & READ UP)

2 – Me:

 image


3 – GBlock:

 image

4 – Me:

 image

So the recommendation is to not program against the container as “It makes parts tightly coupled to host configuration” & “makes code less intentful”.

But as with the deign of modular composition frameworks such as PRISM I found it to be a good fit and it allowed for “reasonably” rapid development of the UI and decoupling of the parts of the View & ViewModel that really mattered.  So I see why it was suggested, but I now also see why they now see it as an anti-pattern.

The universal access to the Container and the Event Aggregator with Composite Events made for very easy composition of a WPF user interface from separate modules, but I would have to agree, now that I have more experience, that programming against the container at this level just felt wrong deep down, and when that is the case you know its just not meant to be.

Please feel free to comment.

1 comment so far

Add Your Comment
  1. Holsee’s Blog » D.I. Container ‘Resolve Self’ – The How & Why not!…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

You must be logged in to post a comment.