It has been some time since I added a post to my blog. I've been quite busy and the first thing that suffers are my blogs. My other one is at http://www.mvcstarterkits.net.
So what is this blog about? It's about Dependency Injection (DI) or Inversion of Control (IoC). There are many DI components available and most of them are open source. The one I'll be demonstrating is one by the folks at the Microsoft Patterns and Practices group call the Unity Application Block.
Unity is a lightweight extensible dependency injection container built for ASP.NET. It promotes loosely coupled objects in your application.
It took me a little while to get my head around why this is necessary but now that I know what it is, I won't be building any application without it. At least for large scale projects.
For more information on Unity, go to http://www.codeplex.com/unity or http://www.pnpguidance.net.
The code for this project is available on my Downloads page.
Most of the examples out there are ok, but they don't really present how to use Unity in an ASP.NET application that is bigger than your home grown web site. So I decided to build one to see how to use it. This is what the first page of this sample project looks like.

If you notice the first three lines, "Hi, from MyFacade", "Hi, from MyService", "Hi, from MyData", these messages are being written from the class in each layer. This is just to prove that I am communicating to each layer as the application loads.
I structured my application into different Visual Studio 2008 projects, each belonging to a separate layer:
- BusinessEntities - contains the entity classes, such as Customer, etc.
- DataAccess - contains the data layer, where you would communicate with the data store
- Services - this sites between the dataaccess layer and the facade layer
- Facade - this is the top most layer, just under the Web layer. All code-behind code talks just to the Facade layer.
- Web - your web site
- Unit Tests - your unit tests

This structure also promotes a pseudo-MVC like framework. You can "almost" test all of your objects in your unit tests and be production ready. I say almost because, you may still need to mock the web UI, but most of the transport of data from the web layer to the infrastructure can be tested in your unit tests without having to mock the UI.
Then I laid the ground work for the different layers to communicate with each other using dependency injection.
I first started at the bottom, the Data Layer, and built a simple class that returns a message from that layer.

It implements IMyData interface which simply has a single method that returns a string called "WriteDataMessage()". This is just to show that I am traversing all layers when the application loads and reads a message from every layer.
Then I go to the Service layer and do something similar, just return a message.

Then I wire up the Facade layer that talks to the Service layer.

The way I build my applications is that my code-behind will talk only to the Facade layer. This helps promote loose-coupling. Notice in every layer, that there is no "new"-ing up of classes, such as MyService service = new MyService();. New-ing up classes tightly-couples your application and does not promote flexibility. This is the basis behind dependency injection.
Also, as any good developer should know, that if you validate on the client, you'll need to validate on the server also. Some user may have their Javascript turned off and you want to make sure their information is good. So I created a generic validator class based on the Microsoft.Practices.EnterpriseLibrary.Validation class.
This class will validate the entity coming in and double check that it's good to go. If it passes, the code will continue to the service call, otherwise, it will throw an exception back up to the UI. This is something you'll need to trap. But I want to do an initial validation in the Facade layer and just send the data to the Service layer.
The Service layer can do more stuff, even more validation and when it's done doing whatever it's doing, it will send the object to the Data layer. And when I build my applications, I want my data layer to just be able to accept the object coming in and act on it. I don't want to do any more validation here. I want my data layer to be dumb, and just do an Insert, or Update, something, but not validate.
SO WHERE IS THE DEPENDENCY INJECTION!
Ok, so now that we have the application somewhat laid out, we can get to the meat of what will make this work.
First we need to make references to the Microsoft.Practices.Unity classes and some other classes in order to make this work.
- Microsoft.Practices.Unity
- Microsoft.Practices.ObjectBuilder2
- Microsoft.Practices.Unity.Configuration
Those are the essentials to make Unity work, but there are other classes used in this project such as: the EnterpriseLibrary.Common and the Validation classes.
There are two (2) different methods for registering your class to interface references:
- Web.config - load all your mapping types in the web.config file (example included in this project)
- C# code (bootstrapper) - load all your mapping types in a class (example also included in this project)
I will address both versions. First let's take a look at the Global.asax class where the registration process takes place for either method.
So after the references are made, we can set up the Global.asax class.

The first line inside the Application_Start method shows the line where the Unity container is created via the GetContainer extension method on the Application class. There is a separate project created for this extension method an a custom HttpModule that does the heavy lifting. You'll find it under the Unity.Library.Web project.
This is the Extension method:

It class essentially new's up a UnityContainer if it doesn't already exist. This is the UnityHttpModule class;

Special thanks goes out to Chris Tavares (creator of Unity) and Michael Puleio for this library snippet. You can find Mike's blog with the code I used at http://blogs.msdn.com/mpuleio/archive/2008/07/17/proof-of-concept-a-simple-di-solution-for-asp-net-webforms.aspx.
What this Unity.Library.Web assembly does is allow ASP.NET applications to easily manage types that need to be registered for the entire application, either via web.config or through code. The UnityHttpModule also recursively walks through your pages and embedded user controls and master pages and injects dependencies where needed. You'll need to add a reference to the HttpModule in the web.config/system.web/httpmodules section.

By making is a separate assembly, you can easily plug the compiled assembly into any future project for easy reuse.
So back in the Global.asax class in the Application_Start method, the "If" block shows you both of the methods you can use to register your classes and interfaces with Unity. The "if" block reads an AppSettings node that simply sets a variable to True or False as to whether to use the Boostrapper method or the web.config method. (You would normally use one or the other method, you wouldn't put this "if" block in your production project. It's just for demonstration purposes.)
BOOTSTRAPPER
The Bootstrapper is just a custom class I made to wrap around all the types I need to register. Here's what it looks like:

It simply maps class implementations to the interfaces, or base classes to interfaces, or concrete classes to base classes. As your needs grow, you can simply add new references in this class and re-compile to make it work.
The way you write your code in the pages code-behind is the same for either method you choose.
Here's what a typical code-behind would look like:

Notice that the Facade property that returns a FacadeBase type is what is injected for this page. This property is then connected to the Facade class and all it's methods and properties.
This would be done for each page in your site. This is similar to the process used in MVC with the View, or Model-View-Presenter (MVP) with the ViewPresenter interface. It doesn't have the same abstraction, but it works.
WEB.CONFIG
If you plan on using the web.config as your location for the mapping types, this is how it can look. The typeAliases node is optional.
Now let's add the information to the web.config file. We make a new Unity section and the types for the classes.

At this point, the application should be ready to go. Let's press Ctrl-F5 and see what happens. You should see this...

As I mentioned at the beginning, the first three lines are dynamic and are executed on page load. If you see this then it works!
I also have some other goodies in this page, including loading the States drop down list control from the Facade class using the ObjectContainerDataSource control, and being able to validate the form using the PropertyProxyValidator control instead of the ASP.NET validation controls.
If you click the Save Customer button you'll see this...

What's happening here is that the PropertyProxyValidator control points to an entity class that you've built and validates against attributes in that class. Here's the Customer class that is validated against.

You set the properties of the PropertyProxyValidator control similar to the normal ASP.NET validation controls, but you point to the class that is going to be validated against and set the property of that class for the validation. Here's the properties window of the PropertyProxyValidator control.

The SourceTypeName is the name of the class, and the PropertyName is the property of that class to validate against for this particular form field, in this case the FirstName property.
Now if you click on the "Page 2" link you will see the second page of the application. You'll notice that it too has three lines of text on the page, but they are a little different. This demonstrates how you can point to other classes specific to a particular page. This is what Page 2 looks like...

You should notice that it says that it's pointing to MySecondFacade, instead of MyFacade. This is done with the web.config and the property on the page 2 code-behind.

Notice that the Facade property has the Dependency attribute with the Name "MySecondFacade" indicator. Since both Facade classes inherit from FacadeBase, this is the way they are identified.
Page 2 also contains a UserControl that also has a dependency on the MySecondFacade base class. Here's a look at the UserControl code-behind:

Well this should give you a better understanding of how Unity works and dependency injection, and how it can be applied to a multi-tiered application.
Again, here are some resources for Unity:
You can find the code in the Downloads page.