Translate

Tuesday, November 8, 2011

C# Dependency Injection tutorial (Inversion of Control Tutorial)


Aim of Dependency Injection:

Referring to the image below. Suppose when the console application was initially built, there was no XML or Text File. But later on an XML datasource is added (and a corresponding GetMessageFromXML class). And a few more months down the line a text file datasource. Our aim is write the code in a way that, when a new datasource is added, only the calling datasource from Main method needs to be updated. The code in DisplayMessage Class shouldn't need to change to accommodate a new datasource.






















Bad code without Dependency Injection:

 What I will try to show you here is how in a bad code, changing one part of the code requires changes in other parts of the code. And how after applying dependency injection,  I could make different parts of code, independent of each other.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{


    class Program
    {
        static void Main(string[] args)
        {
            DisplayMessage dm = new DisplayMessage();
            dm.ShowMessage();
        }
    }

    public class DisplayMessage
    {
        GetMessageFromDatabase Gmd;

        public DisplayMessage()
        {
            Gmd = new GetMessageFromDatabase();
        }
        public void ShowMessage()
        {
            Console.WriteLine(Gmd.GetMessage());
            Console.ReadLine();
        }
    }

    public class GetMessageFromDatabase
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


}



Everything works fine. Suppose 3 months down the line based on the argument passed into the Main method, I have to pull data either from a database or an xml file. To make that happen I add a class GetMessageFromXML to my code. Also I make a slight modification to my Main  method. The code now looks like below.


 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{


    class Program
    {
        static void Main(string[] args)
        {
            DisplayMessage dm = new DisplayMessage(args[0].ToString());

            dm.ShowMessage();
        }
    }


    public class DisplayMessage
    {
        string source;

        public DisplayMessage(string s)
        {
            source = s;

        }
        public void ShowMessage()
        {
            if (source.ToUpper() == "DATABASE")
            {
                GetMessageFromDatabase Gmd = new GetMessageFromDatabase();
                Console.WriteLine(Gmd.GetMessage());
                Console.ReadLine();
            }
            else if (source.ToUpper() == "XML")
            {
                GetMessageFromXML Gmx = new GetMessageFromXML();
                Console.WriteLine(Gmx.GetMessage());
                Console.ReadLine();
            }
          
        }
    }



    public class GetMessageFromDatabase
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


    public class GetMessageFromXML
    {
        public string GetMessage()
        {
            //Pretend this comes from an XML file
            return "Hi from XML";
        }
    }


}

Now another 2 months later suppose I also need to read data from a text file based on the input parameter to the main method. What would I do? I would add another class GetMessageFromTextFile . Also I would have to modify the class DisplayMessage

Do you see how dependent the class DisplayMessage is on the implementation (that is depending on where the data is being fetched from) ?  

Inversion of Control attempts to make the class DisplayMessage  and the data fetching classes totally independent of each other. 

Inversion of control is usually achieved by applying dependency injection. There are three popular ways of applying dependency injection  namely
  • Constructor Injection
  • Method Injection
  • Property Injection

Code with Dependency Injection:


In the code below, I have demonstrated inversion of control using constructor injection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public interface IGetData
    {
        string GetMessage();
    }


    class Program
    {
        static void Main(string[] args)
        {
            IGetData IG;

            string source = args[0].ToString();

            if (source.ToUpper() == "DATABASE")
            {
                IG = new GetMessageFromDatabase();
            }
            else if (source.ToUpper() == "XML")
            {
                IG = new GetMessageFromXML();
            }
            else if (source.ToUpper() == "TEXT")
            {
                IG = new GetMessageFromTextFile();
            }
            else
            {
                IG = new GetMessageFromDatabase();//default set to database
            }

            DisplayMessage dm = new DisplayMessage(IG);
            dm.ShowMessage();


        }
    }


    public class DisplayMessage
    {
        IGetData IGLocal;

        public DisplayMessage(IGetData IG)
        {
            IGLocal = IG;

        }
        public void ShowMessage()
        {
            Console.WriteLine(IGLocal.GetMessage());

        }
    }



    public class GetMessageFromDatabase : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


    public class GetMessageFromXML : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from an XML file
            return "Hi from XML";
        }
    }

    public class GetMessageFromTextFile : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from an Text file
            return "Hi from Text file";
        }
    }
}


Now like you see above, injecting the dependencies through the constructor, I am decoupling DisplayMessage class from the class GetMessageFromDatabase or any other class that the DisplayMessage class might end up utilizing. I can add as many new classes as I want, to fetch data, without modifying the DisplayMessage class, as long as they inherit from the IGetData interface.
So what happened here is that, everything depends on the interface. Which is ideal.


Now you might argue that I actually ended up shifting the dependency to the Main method.  You are absolutely correct. For a console application the main method (or a piece of code called from the main method) is an acceptable composition root (the place where we decide which implementation to use for an interface). The composition root is always located at the startup code of an application. (For web applications that would be global.asax.cs).

In most practical applications you would end up using an Ioc container such as Ninject or Autofac.  These softwares make it possible to inject dependencies (at compile time as well as run time) with much lesser code. Check this for a super simple example of autofac.




12 comments:

  1. Simple.Straight forward explanation of IoC concept with example!!! well done.

    ReplyDelete
  2. real nice tutorial for beginner to understand DI.

    ReplyDelete
  3. simple and good for beginners. well done Vivek

    ReplyDelete
  4. Simply marvellous...

    ReplyDelete
  5. short and to the point. awesome!

    ReplyDelete
  6. thanks this is simple and good

    ReplyDelete
  7. Nice explaination, precise & good example.

    ReplyDelete
  8. Cool ! Does using stored procedure and entity framework takes care of this dependency injection. Because, all my logic are always writing in stored procedures and called using in a class after integration with entity framework. if there are changes, I do it at the database script side

    ReplyDelete

Comments will appear once they have been approved by the moderator