Architecture & DesignWhat is Microsoft Unity Framework?

What is Microsoft Unity Framework?

In this article I will introduce you to the Microsoft Unity Framework and also take you through its dependency injection feature with the help of few sample C# code snippets.

Unity is one among the Microsoft Application Blocks. It is basically introduced as an IOC container by Microsoft, which helps in easy object creation and de-coupling the module dependencies in your project. To use it, just add the reference of the Unity DLLs to your project. The Unity application block can be downloaded from here. It can be useful in your applications to achieve the following.

1. Dependency Injection– Decouples the module dependencies in your application by creating and injecting the object at runtime.

2. Aspect Oriented Programming– Though Unity is primarily an IOC container, it also exposes a feature called interception, which allows the developers to tie the cross cutting concerns to method calls without modifying the actual target object.

In the following section let us look at C# sample codes for Dependency Injection and Interception using Unity.

Dependency Injection using Unity

The dependency of a class can be injected at runtime using the Dependency Injection mechanism. It is a two-step process. Register the dependency and then resolve the concrete business module class. RegisterType and RegisterInstance methods of the UnityContainer classes can be used to perform the Register operation and Resolve method can be used for creating the concrete business class instance.

There are three ways of injecting the dependency to a class or module, they are.

1. Constructor Injection

2. Property Injection

3. Method Injection

The mapping of abstraction and the concrete implementation of the dependency can be done through either configuration file entries or through code directly. The former approach will be a better one as it will not require any kind of code change.

Sample Code

Let us create a sample application and do dependency constructor injection using Unity. Create a Console application and download the Unity application block. Now add reference to the following Unity DLLs to the Console project.

1. Microsoft.Practices.Unity.dll

2. Microsoft.Practices.Unity.Configuration.dll – This one is needed since we go by the config file approach.

Create the class OrderController, which has a dependency to the DataAccess object instance (either be SQL or Oracle). OrderController is the business module concrete class and below is the code.

   public class OrderController
    {
        IDataAccess _dataAccess;
              
        public OrderController(IDataAccess dataAccess)
        {
            _dataAccess = dataAccess;
        }
 
        public void PrintCurrentOrder()
        {
            Console.WriteLine(_dataAccess.GetCurrentOrder()); 
        }
 
        public void PrintAllOrders()
        {
            Console.WriteLine(_dataAccess.GetAllOrders());
        }
    }

Now let us create the IDataAccess derivative classes namely SqlDataAccess and OracleDataAccess.

    public interface IDataAccess
    {
        string GetCurrentOrder();
        string GetAllOrders();
    }
 
    public class SqlDataAccess : IDataAccess
    {
        public string GetCurrentOrder()
        {
            return "Current order object from Sql Database";
        }
 
        public string GetAllOrders()
        {
            return "All orders from Sql Database";
        }
    }
 
    public class OracleDataAccess : IDataAccess
    {
        public string GetCurrentOrder()
        {
            return "Current order object from Oracle Database";
        }
 
        public string GetAllOrders()
        {
            return "All orders from oracle Database";
        }
    }

Go ahead and add the configuration mapping for Unity.

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IDataAccess" type="UnityFramework.IDataAccess, UnityFramework" />
    <namespace name="UnityFramework" />
    <assembly name="UnityFramework" />
    <container>
      <register type="IDataAccess" name="DataAccess" mapTo="OracleDataAccess">
      </register>
    </container>
  </unity>
</configuration>

In the Program.cs add the following code to register the dependency and resolve the OrderController instance as shown below. This will automatically take care of injecting the DataAccess object to the OrderController constructor.

    public class Program
    {
        static void Main(string[] args)
        {
            //Create the unity container
            IUnityContainer container = new UnityContainer();
            //Load unity configuration
            container.LoadConfiguration();
            //Resolve the dependency
            var dataAccess = container.Resolve<IDataAccess>("DataAccess");
            //Register the instance
            container = container.RegisterInstance<IDataAccess>(dataAccess);
            //Resolve for OrderController and the dependecy gets injected automatically
            var controller = container.Resolve<OrderController>();
            controller.PrintCurrentOrder();
            controller.PrintAllOrders();
        }
    }

Run the application and see that OracleDataAccess object is getting injected. Change the config mapping to SqlDataAccess type in order to switch back to SQL.

The same OrderController class can be modified to have Property injection as shown below. Notice the new property DataAccess and the attribute [Dependency] decorating it.

    public class OrderController
    {
        IDataAccess _dataAccess;
        
        [Dependency]
        public IDataAccess DataAccess
        {
            get { return _dataAccess; }
            set { _dataAccess = value; }
        }
 
        public void PrintCurrentOrder()
        {
            Console.WriteLine(_dataAccess.GetCurrentOrder()); 
        }
 
        public void PrintAllOrders()
        {
            Console.WriteLine(_dataAccess.GetAllOrders());
        }
    }

Interception using Unity

Interception in Unity is a feature that can intercept a target object call and execute a series of behaviors before or after the call. It is a feature that enables the Aspect Oriented Programming paradigm in C#. Mostly the cross-cutting concerns like logging, input validation, etc.

I will do a deep dive into the Interception feature of Unity in a future article since I feel this will also be a very useful feature for the C# developers to learn.

Happy reading!

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories