Click here to Skip to main content
15,113,086 members
Articles / Programming Languages / C#
Posted 17 Sep 2008

Tagged as


138 bookmarked

Design Pattern IOC and DI

Rate me:
Please Sign up or sign in to vote.
3.52/5 (53 votes)
27 Mar 2009CPOL9 min read
Design Pattern IOC and DI

Updated with links of Other Application Blocks

Table of Contents


I have been recording and writing on design pattern and UML. You can visit me at  to see my work. In case you like it do not forget to drop me a word at 

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.

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

Part 1 – Design patterns Factory, Abstract factory, builder, prototype, shallow and deep copy, and singleton and command patterns


Part 2 – Design patterns Interpreter, Iterator, Mediator, Memento and observer patterns


Part 3 – Design patterns State, Stratergy, Visitor, Adapter and fly weight pattern


Part 4 - Bridge Pattern , composite Pattern ,  Facade Pattern , Chain od Responsibility , Proxy Pattern , Template Pttern,


Part 1 - UML Interview Questions


Part 2 - UML Interview Questions


You can download by architecture interview question book from 

Other Application Blocks

Validation application blocks: - This article explains the 16 steps you need to perform to do validations using VAB.Validation application blocks

Client side validation: - One of the short comings in VAB is that it does only server side validations. This article talks how we can leverage VAB for client side.Client side validation

Dynamic validation: - This article explains how to build dynamic validation on scenario basis.Dynamic validation

Policy Application blocks: - This article talks how to implement plug and play mechanism using Policy application blocks.Policy application block

Logging application block: - This article explains the 5 basic steps of how to use logging application blocks.
Logging application block

Data application: - This article talks about the four steps you need to implement data application blocks.
Data application block

Exception application block: - This application talks how we can use exception application blocks to log exception from project.Exception application block

UIP block: - This article talks about Reusable Navigation and workflow for both Windows and Web using Microsoft UIP blocks.UIP block


The problem 

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.

Image 1

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.

Image 2

Figure :- Concrete classes

Creational patterns

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).

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.

Image 3

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.

Image 4

Figure: - Containers

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

Solving problem using UNITY block

Now that we know the benefit of containers we will explore unity application block which helps us to achieve dependency injection.

Download and installing Unity

The first step is to download the unity application block from  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.

Image 5

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.

Image 6

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’.

Image 7

Figure: - Import unity namespace

Defining the common interface

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’.

Image 8

Figure: - Database interfaces

Providing the injection gateway

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  .

Image 9

Figure: - Providing injection gateway

Defining the config file

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.

Image 10

Figure: - App.config file

The client code

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.

Finally in step 5 we call the save method

Image 11

Figure: - Client code

The actual internal working

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.

Image 12

Enter the real world of loosely coupling

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

Image 13

Figure: - The real fun



For further reading do watch the below interview preparation videos and step by step video series.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Comments and Discussions

QuestionIOC vs DI vs Service Locator Pin
devvvy22-Dec-14 19:48
Memberdevvvy22-Dec-14 19:48 
here's a good write up[^] comparing IoC, DI and Service Locator

GeneralMy vote of 5 Pin
Mena Armanyous6-Sep-14 11:02
MemberMena Armanyous6-Sep-14 11:02 
Questionnice article Pin
Ajay Kewale9-Dec-12 15:06
MemberAjay Kewale9-Dec-12 15:06 
GeneralMy vote of 5 Pin
zclmoon4-Dec-12 20:18
Memberzclmoon4-Dec-12 20:18 
GeneralVery Nice Article Pin
Member 30853254-Oct-12 0:12
MemberMember 30853254-Oct-12 0:12 
GeneralMy vote of 4 Pin
mr.Sameer-Malhotra21-Jul-12 21:49
Membermr.Sameer-Malhotra21-Jul-12 21:49 
GeneralMy vote of 5 Pin
MemberSATYA NARAYAN SAHOO15-Jun-11 6:31 
GeneralWhere is the source code Pin
dlaub11-Feb-11 6:58
Memberdlaub11-Feb-11 6:58 
GeneralMy vote of 5 Pin
mohammednazeel25-Oct-10 20:41
Membermohammednazeel25-Oct-10 20:41 
GeneralIm finding problem while running this code Pin
Fozia Rehman28-Jan-10 21:24
MemberFozia Rehman28-Jan-10 21:24 
GeneralNice Article! Pin
Iman Mayes29-Mar-09 9:32
MemberIman Mayes29-Mar-09 9:32 
Questionmore than one cls? Pin
Donsw30-Jan-09 15:28
MemberDonsw30-Jan-09 15:28 
GeneralGood article Pin
Donsw21-Jan-09 17:49
MemberDonsw21-Jan-09 17:49 
GeneralWell done! Pin
Ken Hadden31-Dec-08 10:25
MemberKen Hadden31-Dec-08 10:25 
GeneralInteresting but... Pin
Michael Moreno17-Sep-08 23:18
MemberMichael Moreno17-Sep-08 23:18 
GeneralRe: Interesting but... Pin
FZelle18-Sep-08 1:46
MemberFZelle18-Sep-08 1:46 
GeneralRe: Interesting but... Pin
PM51518-Sep-08 4:15
MemberPM51518-Sep-08 4:15 
GeneralRe: Interesting but... Pin
Shivprasad koirala18-Sep-08 4:51
MemberShivprasad koirala18-Sep-08 4:51 
GeneralRe: Interesting but... Pin
PM51518-Sep-08 5:58
MemberPM51518-Sep-08 5:58 
GeneralRe: Interesting but... Pin
Chris Tavares5-Nov-08 12:53
MemberChris Tavares5-Nov-08 12:53 
GeneralRe: Interesting but... Pin
Shivprasad koirala18-Sep-08 4:50
MemberShivprasad koirala18-Sep-08 4:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.