UNITY Framework Tutorial

Posted By:Dhananjay KumarPosted Date:February 25, 2010Points:25
Category: .Net FrameworkURL:http://www.dhananjaykumar.netUNITY Framework Tutorial. This tutorial will explain step by step explanation of how to use UNITY Framework in code. UNITY Framework is a framework of Microsoft to achieve Inversion of Control Design Pattern.

This tutorial will explain step by step explanation of how to use UNITY Framework in code. UNITY Framework is a framework of Microsoft to achieve Inversion of Control Design Pattern.

To know more about, what is Inversion of Control and Dependency Pattern design pattern read my previous article here.

Two very good articles on same topic by Mr ShivPrasad Koirala could be read at following links

Returning instance of the registered type or Resolve an object by the type. ( Task C)

Add a new class in project by right clicking and give name of the class as Factory. Factory is name here; give any name as per desire.

In Factory.cs add namespaces

using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;

Task A: Set Up Container

To set up container, create instance of IUnityContainer class.

The above code will create an instance of container class.

Task B: Register interface as a type

RegisterType method of container class is used to register a type into the container.

At the appropriate time, the container will build an instance of the type which is specified.

The lifetime of the object it builds will correspond to the life time specified in the parameters of the method.

If lifetime is not specified then the type will registered for a transient lifetime, which means that a new instance will be created on each call to Resolve. ( It is method , which will be discussed later)

This method is overloaded with 8 different parameters.

How to register a type?

Task C: Resolve an Object by the type

To resolve an object by type , Resolve method will be used.

To retrieve object instances from the container.

When this method is used without specifying a value for the optional name property, the method returns the object registered with the default mapping.

This method is overloaded with two types of arguments. One takes only type and other argument takes type as well as string name of the registered type.

Hello Dhananjay,This is a very good article for the beginners. But, I am trying to understand the advantages of this approach. You can directly create the object of Player, provide the values to properties, and call the method. Can you please explain why one would want to use Unity in this case? Thanks a lot.