Monday, April 25, 2016

Constructor Dependency Injection Pattern With C#



Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. The term "loosely coupled" deserves clarification and sometimes the best way to explain something is by first describing its opposite, which in this case is "tight coupling." When two classes are tightly coupled, they are linked with a binary association. For example, you can see in the below code, Calculate and ErrorHandler, that are joined together as an aggregation. 

Without Constructor Dependency Injection Pattern 

create an interface IErrorHandler which has one method to show the Error occurred. 

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

namespace DependencyInjectionApplication
{
    public interface IErrorHandler
    {
        void showError(string erroMessage);
    }

}

Next create a class called ErrorHandler, which inherits the IErrorHandler interface and implement it's showError method, which we are going to use to show the Error message. 


using System;

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

namespace DependencyInjectionApplication
{
    class ErrorHandler : IErrorHandler
    {
     
        public void showError(string erroMessage)
        {
            Console.WriteLine(erroMessage);
        }
      
    }
}

Now lets create a another class called Calculate to understand the concept of tight coupling. 



using System;

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

namespace DependencyInjectionApplication
{
    public class Calculate
    {
        IErrorHandler errorHandler = new ErrorHandler();
        public void calcValues()
        {
          
            try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }


        }
    }
}

Above class has an interface IErrorHandler instance which reference the ErrorHandler class. because of this the Calculate class is tightly coupled with the ErrorHandler class. 

Now lets call the calcValues method from main class.



using System;

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

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Calculate calculate = new Calculate();
            calculate.calcValues();        

            Console.ReadLine();
        }
    }
}

this will show the below output, but as you can see this is not a good design because of tightly coupled.


With Constructor Dependency Injection Pattern 

The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.

Advantages
  • Construction Injection makes a strong dependency contract
  • Construction Injection supports testing, because dependencies can be passed in the constructor.
  • A dependency may be made immutable by making the dependency reference final by means that it prevents circular dependency.
Disadvantages
  • It requires up front wiring of the entire dependency graph.
The class that needs the Dependency must be exposing a public constructor that takes dependent class as constructor argument. In most cases, this should be the only one available constructor but if more than one Dependency is required then additional constructor arguments can be used.


Now lets create a CalculationEvent, That class has a parameter constructor. This constructor will be used to inject dependencies in the object. 

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

namespace DependencyInjectionApplication
{
    public class CalculationEvent
    {
        IErrorHandler errorHandler;

        public CalculationEvent(IErrorHandler errorHandler)
        { 
            this.errorHandler = errorHandler;        
        }

        public void PerformCalculation()
        {
             try
            {
                int no1 = 20;
                int no2 = 0;
                int total = no1 / no2;
                Console.WriteLine("Result is : " + total.ToString());
            }
            catch (DivideByZeroException ex)
            {
                errorHandler.showError("Can't Divide Value By 0");
            }
        }
    }
}

you can see that the CalculationEvent class is not depend on any other class. 


using System;

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

namespace DependencyInjectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            CalculationEvent calculationEvent = new CalculationEvent(new ErrorHandler());
            calculationEvent.PerformCalculation();

            Console.ReadLine();
        }
    }
}