DotNet

Dependency Injection with Microsoft Unity Application Block


 

I‘ll discuss about dependency injection pattern and its implementation using Microsoft Unity Application BlockFirst we start with what is Dependency Injection.

What is Dependency Injection?

DI is also known as Inversion of Control (IOC). It is a design pattern that remove tight coupling between dependent components. It facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies that often inhibit reuse. Instead of compile time dependencies it offers runtime loading and initialization of components, which makes solutions load on demand.

There are following advantages and disadvantages of Dependency Injection

Primary advantages:

  • Loose coupling
  • Centralized configuration
  • Easily testable

Disadvantages:

  • Debugging components while development because finding concrete objects may be tedious task.It make code harder to understand and more difficult to modify.
  • Wiring instances together can become a nightmare if there are too many instances and many dependencies that need to be addressed.

Different types of Dependency Injection

  1. Constructor Injection
  2. Setter Injection
  3. Interface-based injection

Constructor Injection

In this injection type, dependencies can be injected through parameters in constructor of class. It is widely used in Unit Testing with Mocking objects.

Here is example (Please note: this example is not real solution of credit card validation, it is just for example purpose).

public class CreditCardValidator
    {
        private ICreditCard _card;

        public CreditCardValidator(ICreditCard card)
        {
            _card = card;
        }

        public bool Validate()
        {
            return _card.Validate();
        }
    }

In below code I am injecting instance of VisaCard and MasterCard classes from outside to validate card no.

    public interface ICreditCard
    {
        string CardNo { set; }
        bool Validate();
    }
    public class MasterCard : ICreditCard
    {
        private string _cardno;
        public bool Validate()
        {
            return true;
        }

        public string CardNo
        {
            set { _cardno = value; }
        }

    }
    public class VISA : ICreditCard
    {
        private string _cardno;

        public bool Validate()
        {
            return true;
        }

        public string CardNo
        {
            set { _cardno = value; }
        }
    }

 static void Main(string[] args)
        {
            ICreditCard visaCard = new VISA();
            visaCard.CardNo = "123123123";
            ICreditCard mastercard = new MasterCard();
            visaCard.CardNo = "456456456";

            Console.WriteLine("Validate Card");
            CreditCardValidator validator = new CreditCardValidator(visaCard);
            Console.WriteLine("Validating Visa Card Result: {0}", validator.Validate());
            validator = new CreditCardValidator(mastercard);//again creating instance
            Console.WriteLine("Validating Master Card Result: {0}", validator.Validate());

            Console.ReadLine();
	}

}

Output

Validate Card

Validating Visa Card Result: True

Validating Master Card Result: True

Setter Injection

Setter injection uses properties to inject the dependencies, which lets you create and use resources as late as possible. It’s more flexible than constructor injection because you can use it to change the dependency of one object on another without having to create a new instance of the class or making any changes to its constructor.Here’s an example which will inject creditcard instance through properties in that case we don’t need to create instance of CreditCardValidator again.

   public class CreditCardValidator
    {
        private ICreditCard _card;

        public ICreditCard Card
        {
            get { return _card; }
            set { _card = value; }
        }

        public bool Validate()
        {
            return _card.Validate();
        }
    }
 	static void Main(string[] args)
        {
            ICreditCard visaCard = new VISA();
            visaCard.CardNo = "123123123";
            ICreditCard mastercard = new MasterCard();
            visaCard.CardNo = "456456456";

            Console.WriteLine("Validate Card");
            CreditCardValidator validator = new CreditCardValidator();//creating instance one time only
            validator.Card = visaCard;//setter injection
            Console.WriteLine("Validating Visa Card Result: {0}", validator.Validate());
            validator.Card = mastercard;//setter injection
            Console.WriteLine("Validating Master Card Result: {0}", validator.Validate());

            Console.ReadLine();
            return;
        }

Interface Injection

Interface injection, by using a common interface that other classes need to implement to inject dependencies.

The following code shows an example in which the classes use the ICreditCard interface as a base contract to inject an instance of any of the credit card classes (VISA or MasterCard) into the CreditCardValidator class. Both the credit card classes VISA and MasterCard implement the ICreditCard interface:

 public interface ICreditCard
    {
        string CardNo { set; }
        bool Validate();
    }

    public class MasterCard : ICreditCard
    {
        private string _cardno;
        public bool Validate()
        {
            return true;
        }

        public string CardNo
        {
            set { _cardno = value; }
        }

    }
    public class VISA : ICreditCard
    {
        private string _cardno;

        public bool Validate()
        {
            return true;
        }

        public string CardNo
        {
            set { _cardno = value; }
        }
    }

Dependency Injection with Unity Application Block

The Unity Application Block (Unity) is a lightweight extensible dependency injection container with support for constructor, property, and method call injection.

Unity is a general‐purpose container for use in any type of .NET Framework‐based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.

Why you should implement Unity ?

  • You wish to build your application according to sound object oriented principles (following the

    five principles of class design, or SOLID), but doing so would result in large amounts of

    difficult‐to‐maintain code to connect objects together.

  • Your objects and classes may have dependencies on other objects or classes.
  • Your dependencies are complex or require abstraction.
  • You want to take advantage of constructor, method, or property call injection features.
  • You want to manage the lifetime of object instances.
  • You want to be able to configure and change dependencies at run time.
  • You want to intercept calls to methods or properties to generate a policy chain or pipeline containing handlers that implement crosscutting tasks.
  • You want to be able to cache or persist the dependencies across post backs in a Web application.

Constructor Injection with Unity

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;

namespace ParallelLibrarySamples
{
    class Program
    {
       
	 static void Main(string[] args)
        {
            
            IUnityContainer uContainer = new UnityContainer();
            uContainer.RegisterType();
	    //it will automatically fires constructor of CreditCardValidator class
            CreditCardValidator myInstance = uContainer.Resolve();
	}
     }

 public class CreditCardValidator
        {
            public CreditCardValidator(ICreditCard card)
            {
		//card is VISA type
                card.Validate();
            }
	}
}

First you need to register interface with concrete object,

uContainer.RegisterType();

when you call resolve method of instance IUnityContainer, it will call constructor and find concrete object from IUnityContainer.

Setter Injection with Unity

For property injection you just need to put [Dependency] attributes on property, Unity framework will automatically create concrete object. The following code demonstrates property injection.

static void Main(string[] args)
        {
            
            IUnityContainer uContainer = new UnityContainer();
            uContainer.RegisterType();

           // CreditCardValidator myInstance = uContainer.Resolve();
            CreditCardValidator myinstance = new CreditCardValidator();
            myinstance.Validate();
	}
	public class CreditCardValidator
        {
            
            private ICreditCard _card;
            
            [Dependency]
            public ICreditCard Card
            {
                get { return _card; }
                set { _card = value; }
            }

            public bool Validate()
            {
                return _card.Validate();
            }
        }

REFERENCES

http://unity.codeplex.com/

http://martinfowler.com/articles/injection.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s