Geeks With Blogs
Rajesh Pillai My experiments with asp.net mvc, jquery, wpf, silverlight, sharepoint, tdd and design patterns.

Just to give you a background to all those who newly following this post,we will be publishing materials of this kind every week to gain some
insight into upcoming technologies, to understand current technology better, to know more about the latest development processes, best practices, build up
foundational skills, RIA, certifications etc. etc.


The intent is very clear.   To get out of the routine work mode and build something for ourselves, because the more the stronger we become in these said
areas the better it is for our work.

Let’s come to the point.  Today’s topic is “Dependency Injection and IOC”.


PREREQUSITE FOR THIS MATERIAL :  The SOLID principle (Refer my earlier mail)


We all have come across this term “Dependency Injection” at one point or other in our work life.  Let us all try to nail it down.


“Dependency Injection (DI)” refers to the process of supplying an external dependency to a software component.  It is a specific form of inversion of control (IOC)
where there concern being inverted is the process of obtaining the needed dependency.  The term was first coined by Martin Fowler to clearly describe the mechanism.

 

Wiki URL : http://en.wikipedia.org/wiki/Dependency_injection


NOTE:

“ IOC is a key part of what makes a framework different from a library.  A library is essentially a set of functions that you can call, these days usually organized
into classes.  Each call does some work and returns control to the client. 


A framework embodies some abstract design, with more behavior built in.  In order to use it you need to insert your behavior into various places in the framework
either by subclassing or by plugging in your own classes.  The framework’s code then calls your code at these points.  “


IOC is based on the “Hollywood Principle”, “Do not call us, we will call you”.

Two important principles of IOC

·         High level classes should not depend on the direct implementation of low level classes or aggregated classes.  Both the classes should depend on abstraction. 
Remember the SOLID (D – Dependency Inversion Principle)
.  So, the Project class should not depend directly on the Employee class.  Both should depend on a
abstraction either using interface or abstract class.

·         Abstraction should not depend on details, details should depend on abstraction.
Ok, let’s move on.

First,  “Every Solution needs a problem”.  Does this statement rings in your ear?   So, what problems  are solved by Dependency Injection?

 

·          It makes your application truly loosely coupled.·        
It provides a way to extend your application (you can inject your dependencies based on some configuration).

It enable you to unit test your code (as you can easily inject fake dependencies to test your core logic).

·         It removes the rigidity out of your application. 

Take this example 

    public class Employee
    {
        public Employee()
        {

        }
    }


    public class Project
    {
        private Employee _emp;  
        public Project()
        {
            _emp = new Employee();       // 1. Aware of concrete classes.
        }
    }


The main problem with the above class structure is that it is aware of its dependencies.  This awareness may limit this object from being extensible.  We
have taken a rudimentary example here as our main intent is to understand the DI/IOC.


Have a look at this modified classes. 

    public interface IEmployee { }; 

    public class Employee : IEmployee
    {
        public Employee()
        {
        }
    }

    public class Project
    {
        private IEmployee _emp;  
        public Project()
        {
            this._emp = new Employee();  // we still have a problem here as we are directly ref. concrete object.
        }
    }


The dependencies to concrete object Employee is now removed but the construction of Employee is still directly done.  Now this construction has to be moved
away from project class and has to be injected externally. 

There are four ways to inject this dependency, which is outlined below:

·         Constructor way

The framework code

private IEmployee _emp;

public Project(IEmployee emp)
{
    this._emp = emp;
}   


The client code
public class Client
{
        Project proj = new Project(new Employee());
}

·        
Setter and Getter

The framework code
public IEmployee Employee

{

     get
      {  return this._emp;      }
     set      {  this._emp = value;    }
}

The client code
public class Client
{

      Project proj = new Project();
      proj.Employee = new Employee();

 }

·         The Interface method

The framework code

public interface IEmployeeDI
{
       void SetEmployee(IEmployee emp);
}

public class Project : IEmployeeDI
{
        private IEmployee _emp;
        public void SetEmployee(IEmployee emp)
        {
            _emp = emp;
        }
}

 

The client code

public class Client
{
        Project proj = new Project();
        public Client()
        {
            proj.SetEmployee(new Employee());
        }
}


The Service Locator Pattern :  The main class will use the Service Locator you aggregate the child object (Employee in this case).  The Service Locator
does not create instances of the Employee object, it provides a methodology to register and find services which will help in creating objects.  We will look
at this patter later on when we are dealing with enterprise patterns.

                         The framework code

public static class LocateEmployee
{
       public static IEmployee GetEmployee()
       {
            // your method goes here....
        }

}

public class Project
{
        private IEmployee _emp;
        public Project()

        {
            this._emp = LocateEmployee.GetEmployee();  // Call the Employee Locator
        }
}

 We  now have knowledge about how to  inject the dependencies into our objects manually.  In the next series of technomails, we will specifically have a look at the well known
DI frameworks/IOC containers like , Unity Block, StructureMap, Castle Windsor etc. as time permits and also some of the design benefits and some  real world scenarios.

 Hope you enjoyed this series.  Do definitely ponder over this.  Though this may seem very preliminary, but it has a huge impact on the design.

 

P.S:  Do feel free to correct any mistakes if any or clear any ambiguity if any exist

Posted on Saturday, November 28, 2009 11:06 AM IOC , Dependency Injection | Back to top


Comments on this post: Tech Mastery : Dependency Injection and IOC

# re: Tech Mastery : Dependency Injection and IOC
Requesting Gravatar...
Good Intro article.

It would be great if you can add details about pros and cons of various dependency mechanism and the related framework. For e.g I feel Constructor Injection is the best way to go followed by Service Locator. There are framework that supports different ways of dependency injection. For e.g Spring started with Setter and Getter based approach but now supports Constructor based injection also.
Left by Sunil Unnithan on Jan 07, 2010 5:59 PM

# re: Tech Mastery : Dependency Injection and IOC
Requesting Gravatar...
Will cover that in future post. Glad you like it.
Left by Rajesh Pillai on Jan 12, 2010 6:50 PM

Your comment:
 (will show your gravatar)


Copyright © Rajesh Pillai | Powered by: GeeksWithBlogs.net