Unity Application Block (Unity) is a lightweight, scalable, dependency injection container developed by the Microsoft Patterns & practices team to help build loosely coupled systems. It supports constructed child injection (constructor injection), attribute/Set Value method injection (Property/setter injection), and method invocation injection (methods call injection). The Patterns & practices team released the first official version of Unity (Unity 1.0) a few days ago (April 4).
Preparatory work
First look at some of the interfaces and classes, which will be used below:
public interface IPlayer
{
void Play ();
}
public class Mp3player:iplayer
{
public void Play ()
{
Console.WriteLine ("Playing Mp3");
}
}
public class Cdplayer:iplayer
{
public void Play ()
{
Console.WriteLine ("Playing CD");
}
}
public class Dvdplayer:iplayer
{
public void Play ()
{
Console.WriteLine ("Playing DVD");
}
}
Start with a simple example
//创建Unity容器
IUnityContainer container = new UnityContainer();
//注册类型映射
container.RegisterType<IPlayer, Mp3Player>();
//获取对象实例,由于上一步已在容器中将IPlayer接口映射为Mp3Player类,
//所以这里会自动装载Mp3Player类,创建该类的实例
IPlayer player = container.Resolve<IPlayer>();
//调用实例方法
player.Play();
The output is: