How to resolve instance of registered type?
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
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:
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
Future scope
In the next article, I will explain how
- To register an existing object instance as an externally controlled instance
- To register an existing object as a singleton instance
How to use zip file
Just download and use it.
Download UNITY Framework also. Add references as shown in above steps. Then run the code.