In the previous article we discussed about the fundamentals of IOC and DI design patterns. In case you have missed it you can read more about it on the following link IOCDI.aspx

In the same article we also discussed about how Windsor can be used to solve this problem. In this article we will take up a simple example and try to implement DI using unity application blocks thus resulting in loosely coupled architecture.

Lately I have been writing and recording videos heavily on design patterns , UML and many architectural stuff you can visit http://www.questpond.com for design pattern and UML videos.

You can read my previous articles on design patterns and UML in the below links:-

Any good architecture always stands on the base that components are loosely coupled… let me stress the point truly loosely coupled. Let’s try to understand this with a scenario and how we normally approach this problem using pure object oriented way.

Consider a scenario where we have a customer class which needs to perform insert operation on database. The customer class should be customizable to save in either Sql server or oracle database. In future we should also be able to add new databases with out disturbing the customer class.

Below is what we will do. Define two classes one for SQL server and other for Oracle. Both these classes inherit from some kind of same interface ‘Idatabase’. The customer class points to this interface. So the customer class is theoretically shielded from the concrete implementation of SQL Server or oracle. But because the object creational activity needs to be done by the customer class it still needs to be aware of the concrete classes.

Figure: - General loosely coupled thinking

This is what will happen in actual implementation as shown in figure ‘Concrete classes’. The customer class will be creating objects of either oracle or SQL server depending on condition. That means the customer class is exposed to the concrete classes which defeats the purpose of interface. Any change in the database classes will lead to compiling of the customer class.

The next thing comes in mind is creation patterns. If we can introduce a factory who takes the creational aspect of the concrete classes thus isolating the concrete classes from the customer class.

Here are the issues with factory which makes us force to think about some other solutions:-

• Everything is hardcoded: - The biggest issues with factory are it can not be reused across applications. All the options are hardcoded in the factory itself which makes the factory stringent to particular implementation.• Interface dependent: - The base on which factories stands are common interfaces. Interfaces decouple the implementation and the object creation procedure. But then all the classes should implement a common interface. This is a limitation by itself again.• Factories are custom: - They are very much custom to a particular implementation.• Everything is compile time: - All dependent objects for an object in factory have to be known at compile time.

I will not be explaining factory pattern in case you are not aware of you can read the same in my previous article SoftArchInter1.aspx

Ok, I will show you a magic…Rather than writing those huge line of code for factory…lets go the DI way (Dependency injection).

Rather than writing factory pattern, how about injecting the object directly in to the customer class. So let the customer class references the interface and we should be able to inject the concrete type in to the customer class. With this the customer class does not need to use the new keyword and is complete decoupled from the concrete classes.

Figure: - Dependency injection

Injection can be done using containers. So basically you need to put both the classes in to the container and the container will create object and inject the same in to the other class.

Figure: - Containers

With this your customer class does not need to worry about creating objects and knowing the concrete objects.

The first step is to download the unity application block from http://msdn.microsoft.com/en-us/library/cc468366.aspx and install the same. Depending on whether you have 2008 or 2005 the documentation will vary. For this tutorial I will be using VS 2005 because majority professionals are still using 2005.

Figure: - unity block installed

Once you install the block you should be able to see the same in Microsoft patterns and practices.

The first thing you need to do is to get the references of at least two components Unity and Unity configuration.

Figure: - Add referenced to Unity components

Once you have got reference to the components import the “Microsoft.Practices.Unity” namespace in to your code as shown in figure ‘Import unity namespace’.

As said previously we should be able to inject SQL Server database object or oracle database object in the customer class. So as a good practice we will inherit the SQL server implementation and oracle implementation from a common interface ‘Idatabase’.

In the customer class we will reference the interface and expose the public property using [Dependency] attribute. This exposure is essential for the unity container. Unity container needs some kind of gateway by which it can inject the object. So what we have done is we have exposed the interface ‘iDatabase’ publicly. There are lot of other ways by which we can achieve the same you can read my previous article on the different ways of providing injection gateways for containers IOCDI.aspx .

To achieve high customization unity application allows us to specify how the injection will work in the config files ( web.config and app.config ). As this example is a windows command application we will be defining an app.config file.

You can see below a simple template of App.config file from unity perspective. The Configsection is compulsory and keep it as it is. The important section to be noted is the types section which comes under container section. In this we specify which interfaces map to which concrete class. The unity container creates object from this section and inserts in to the customer object through the dependency attribute.

The client code is pretty simple. The first step us we create the unity container object. In the second step we read the unity section. In step 3 we configure the container using the unity section data.

In step 4 we tell the container to create the customer object. This is the most important step of all. In this the container using the config data and the dependency attribute injects either the SQL server database object or oracle database object in to the customer class. This object creation depends on what is defined in the app.config file.

So what happens internally in the container is that the unity container creates the object of either oracle or SQL server data objects and injects in to the customer class through the dependency defined attribute.

So if you define the ‘clsSqlServer’ class it will create the object of ‘clsSqlServer’ and inject it in to the customer class. If you define the ‘ClsOracle’ class it will inject the ‘clsOracle’ object. You can see in figure ‘The real fun’ how easy it to change implementation by just modifying the config file type sections

Question: I understand the pattern for a single class but what happens if you add another class along with clscustomer, such as clsorder. Do you have duplicate Idatabase, clssqlserver and clsoracle since the routines in them would be different for each clscustomer and clsorder?

I find that this is interesting like all your previous pattern articles. In my humble opinion there is a major flaw with this technique though: it uses the config file.

Config files can be over used, over complicated and completely unmaintainable for large applications with many executables and many clients. In my experience I find that almost any problem in a config file will prevent the application from starting and finding where the problem comes from is a major headache.

So this is an interesting technique that personally I will stay well clear of for Database classes which we can count in the many hundreds in most applications.

Having said that, for other usage, where the number of classes is much lower that may make sense. But then using factories may suffice.

The Unity DI framework is being used throughout this article. Actually, the heading at the top of the article reads Loosely coupled architecture using unity application blocks....

Unity, being a product of Microsoft Patterns & Practices, is obviously config file centric. I do agree that XML config can become a nightmare. Personally, for DI I am currently using Ninject[^] and love its simplicity and fluent interface (i.e. no-angle brackets) for object registration. Autofac[^] is also high on my list, but since it makes heavy use of lambda expressions for configuration and I am stuck with a .Net 2.0 build system and compiler for now, I haven't used it.

The general idea of this article in terms of the "design using contract" philosophy is point on in terms of the DI/IOC core principle of loose coupling. The only other criticism I would add, as it relates to Unity is that I don't care for the use of the attributes for decorating injection targets. It's nice to be as loosley coupled to your DI framework as possible, too.

Yes, I agree. Complexity is not good! To me, though, I find XML configuration and attribute decorating much more complex than Ninject and Autofac's fluent interface and ability to not require attribute decoration.

As the author of Unity, let me clarify a couple of misconceptions here.

First off, Unity is not "config file centric." The config file is one way to configure the container, but it's not the only way. In fact, the configuration support is in a separate assembly specifically so that those who don't want to use conf files don't have to.

Similarly, the attributes are one way to configure what gets injected, but isn't the only one. You can do this either through the config file or using our API.

The equivalent API for Unity 1.2 (just shipped last week!) to the config file in the article is:

container.RegisterType<iDatabase>();

To eliminate the [Dependency] attribute, you need to do this to configure the container:

Hi,
Yes it can become cluttered if the config file is not mnaganed properly. But i am sure the factory class can also become too much complex if the scenario is really complex. So from my perspective i would rather go for DI using any container as i would not require to compile huge time. The only doubt which i will have is how much can i trust those container. I am not saying unity is the best....I am myself experimenting around it.

If i think about implementing these things in live projects

--- Will i get a performance hit
--- How much can i trust and how much are they configurable. When i say trust do they have any kind of defects which will show off after go live.