Saturday, March 22, 2008

Auto-wiring an MVC Triad using Unity

I think this post's title is a little bit cryptic, but if you did understood my intentions; you are possibly an IoC geek and may be you know what I am trying to say here.

So, let me explain the phrase from right to left:

Unity: The Unity Application Block (Unity) is a lightweight, extensible dependency injection container with support for constructor, property, and method call injection; it will be part of Entrprise Library version 4.0 and it has its own space on codeplex (www.codeplex.com/unity )

MVC : The famous Model-View-Controller design pattern used in the presentation layer since its invention in the 70s.

Wiring: The MVC pattern requires 3 classes to exist and coordinate together, the Controller class will need an instance of the Model and View, and the View will need a reference to the Model so it can handle the display of the Model.

In the normal life of any MVC based application, we will need some code like this:

Model m = new Model();

View v = new View();

Controller c = new Controller ( m , v);

c.Start();

By this; I mean wiring the classes together so they will be able to communicate.

Auto-Wiring: Is the mechanism of automatically wiring the classes together without the need to write the above code again and again.

One of the auto-wiring techniques is to use the Dependency Injection pattern, and instead of building my own implementation of it, I am using the Unit Application Block.

Unity is able to discover the dependency of the classes based on their constructors, so in the above example; Unity will discover that Controller will need a Model and a View instance so the Controller can be instantiated, and also the same for the View.

Using Unity, all what is needed is to call the Resolve method in the UnityContainer and it will instantiate all the dependencies for us (namely the Model and the View), and will instantiate the controller and pass it the created instances auto-magically.

UnityContainer container = new UnityContainer();

Controller c = container.Resolve<Controller>();

c.Start();


I have made a sample application, you can check to see the above code into action. You will need VS2008,no need to download or setup Unity, since its assemblies are included.



Agree, Disagree? I like to hear your comments.


No comments: