Introduction Unity Framework

No.of Views3142
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  04 May 2010 11:05:46
Tag : .NET Frameworks , General
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.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Objective

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 Click here.

How to use UNITY Container

Step 1

Download UNITY application block from Here

Step 2

Create New Project and Console application.

Step 3

Add reference to  
Microsoft.Practices.Unity ,Microsoft.Practices.Unity.Configuration;

 

Image Loading

Step 4

Right click on project and add new item and then select interface. Give name of the interface as IPlayer.
 

Image Loading

Type below code in IPlayer.cs .  This interface will registered as type to Unity Container.

IPlayer.cs

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

namespace UnityTesting
{
   public  interface IPlayer
    {
       string PlayerName
       {
           get;
           set;
       }
       string TeamName
       {
           get;
           set;
       }

         void DisplayDetails();
    }
}

Step 5

Right click on project and add new class.  Give name of the class as Player.cs
Note: Player class is implementing IPlayer interface. 

 

Image Loading

Type below code in Player.cs

Player.cs

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

namespace UnityTesting
{
     public class Player:IPlayer 
    {
         public Player()
         {
         }
         
         string name;
         string teamName;
        
         public string PlayerName
         {
             get 
             {
                 return name; 
                 
             }
             set
             {
                 name = value; 
             }

         }
         public string TeamName
         {
             get
             {
                 return teamName; 
             }
             set
             {
                 teamName = value; 
             }
         }
       public void DisplayDetails()
         {
             Console.WriteLine("Player Name = \t" + name + " \tPlayer Team Name = \t" + teamName);
             //Console.WriteLine(p.PlayerName);
         }


    }
}

Step 6



Factory Class: This is a class, which is responsible for
1.    Setting up the Unity Container.  (Task A)
2.    Registering interface as a type to the container.  (Task B)
3.    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.

 

Image Loading

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.

IUnityContainer _container = new UnityContainer();

The above code will create an instance of container class.

Task B:   Register interface as a type

1.    RegisterType method of container class is used to register a type into the container.
2.    At the appropriate time, the container will build an instance of the type which is specified.
3.    The lifetime of the object it builds will correspond to the life time specified in the parameters of the method.
4.    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)
5.    This method is overloaded with 8 different parameters.
 

Image Loading

How to register a type?

Image Loading

Task C:   Resolve an Object by the type

1.    To resolve an objcet by type , Resolve method will be used.
2.    To retrieve object instances from the container.
3.    When this method is used without specifying a value for the optional name property, the method returns the object registered with the default mapping.
4.    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.
 

Image Loading

How to resolve instance of registered type?

IPlayer obj = _container.Resolve<IPlayer>();


If exact return type of instance is known then that could be also applied like

Player obj1 = _container.Resolve<Player>();

 

Putting altogether the Factory class.
 

Factory.cs

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

namespace UnityTesting
{
     public class Factory
    {
         static public IPlayer CreateInstance()
         {
             IUnityContainer _container = new UnityContainer();
             _container.RegisterType(typeof(IPlayer), typeof(Player));
             IPlayer obj = _container.Resolve<IPlayer>();
             return obj;
         }
    }
}

Explanation

CreateInstance() is a static method. This method will return instance of type registered to the container.

Step 7

Now solution explorer should look like  as below

 

Image Loading


Step 8

Click on Program.cs and paste below code

Program.cs

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

namespace UnityTesting
{
    
    class Program
    {
        static void Main(string[] args)
        {
            IPlayer obj = Factory.CreateInstance();
            obj.PlayerName = " Sachin Tendulkar ";
            obj.TeamName = " India "; 
            obj.DisplayDetails();
            IPlayer obj1 = Factory.CreateInstance();
            obj.PlayerName = " Shane warne";
            obj.TeamName = " Australia ";
            obj.DisplayDetails();
            Console.Read();
            
        }
    }
}

Explanation

IPlayer obj = Factory.CreateInstance();
This code is used to create a instance if type Player using Unity Container.

obj.PlayerName = " Sachin Tendulkar ";
            obj.TeamName = " India "; 
            obj.DisplayDetails();


Now properties and methods of class being called using instance of the class. Here Each time calling Resolve method is returning an instance of registered type , because time line is variant and not specified.

Output SnapShot

Image Loading

Conclusion

This article has explained , How yo use UNITY Container  using the code .

Future scope

In next article, I shall explain how to
1.     To register an existing object instance as an externally controlled instance
2.    To register an existing object as a singleton instance

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company- Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top