Saturday, June 6, 2015

Using Unity IOC Container for Dependency Injection


What is it?

  • Unity is an IOC container for .NET
  • Unity can be installed in any .NET project using Nuget

Usage Example


using System;
using Microsoft.Practices.Unity;

namespace IOCUnityTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create the container for objects
            UnityContainer unityContainer = new UnityContainer();

            // Tell container how to resolve types
            unityContainer.RegisterType<IProducts, Products>();
            unityContainer.RegisterType<IShipping, FixedShipping>(
                new ContainerControlledLifetimeManager());  // singleton

            // Have the container create an instance of invoice
            var invoice1 = unityContainer.Resolve<Invoice>();
            Console.WriteLine("Invoice 1 Total: " + invoice1.Total);

            // Change what IShipping resolves to (FreeShipping)
            unityContainer.RegisterType<IShipping, FreeShipping>();
            var invoice2 = unityContainer.Resolve<Invoice>(); 
            Console.WriteLine("Invoice 2 Total: " + invoice2.Total);
        }
    }

    interface IProducts
    {
        decimal SubTotal { get; set; }
    }

    interface IShipping
    {
        decimal ShippingCharge { get; set; }
    }

    class Products : IProducts
    {
        public decimal SubTotal
        {
            get
            {
                return 10;
            }
            set { }
        }
    }

    class FixedShipping : IShipping
    {
        public decimal ShippingCharge
        {
            get
            {
                return 5;
            }
            set { }
        }
    }

    class FreeShipping : IShipping
    {
        public decimal ShippingCharge
        {
            get
            {
                return 0;
            }
            set { }
        }
    }

    class Invoice
    {
        IProducts _products;
        IShipping _shipping;
        public Invoice(IProducts products, IShipping shipping)
        {
            this._products = products;
            this._shipping = shipping;
        }

        public decimal Total
        {
            get
            {
                return this._products.SubTotal + this._shipping.ShippingCharge;
            }
        }
    }
}