Unity 简单示例代码和向导/Unity Aplication Block
Unity 简单示例代码和向导
关于Unity 的说明和下载地址,请访问[微软控制反转和依赖注入容器Unity 1.0发布] http://forum.entlib.com/Default.aspx?g=posts&t=25 。
下面的范例主要实现:首先,定义ILogger 接口。然后,定义一个实现该接口的具体类 ConsoleLogger。其次,定义一个业务类 CustomerTasks,通过constructor 函数注入ILogger 依赖类,并在CustomerTasks 的其中一个方法内调用 ILogger 的Log方法。
1. 定义ILogger 接口。
namespace UnitySamples
{
public interface ILogger
{
void Log(string message);
}
}
{
public interface ILogger
{
void Log(string message);
}
}
2. 定义ConsoleLogger类,实现ILogger 接口。
namespace UnitySamples
{
public class ConsoleLogger : ILogger
{
public ConsoleLogger()
{
Console.WriteLine("Hello from constructor");
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
}
{
public class ConsoleLogger : ILogger
{
public ConsoleLogger()
{
Console.WriteLine("Hello from constructor");
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
}
3. 定义业务类CustomerTasks。
namespace UnitySamples
{
//create a class that takes an ILogger through constructor injection.
public class CustomerTasks
{
private readonly ILogger logger;
public CustomerTasks(ILogger logger)
{
this.logger = logger;
}
public void SaveCustomer()
{
logger.Log("Saved customer");
}
}
}
{
//create a class that takes an ILogger through constructor injection.
public class CustomerTasks
{
private readonly ILogger logger;
public CustomerTasks(ILogger logger)
{
this.logger = logger;
}
public void SaveCustomer()
{
logger.Log("Saved customer");
}
}
}
创建CustomerTasks类,该类通过constructor 函数注入ILogger依赖类。
4. 使用UnityContainer 依赖注入容器。
using Microsoft.Practices.Unity;
namespace UnitySamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>(new ContainerControlledLifetimeManager());
CustomerTasks tasks1 = container.Resolve<CustomerTasks>();
CustomerTasks tasks2 = container.Resolve<CustomerTasks>();
tasks1.SaveCustomer();
tasks2.SaveCustomer();
}
}
}
namespace UnitySamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>(new ContainerControlledLifetimeManager());
CustomerTasks tasks1 = container.Resolve<CustomerTasks>();
CustomerTasks tasks2 = container.Resolve<CustomerTasks>();
tasks1.SaveCustomer();
tasks2.SaveCustomer();
}
}
}
通过RegisterType 方法注册ILogger 为Singleton 实例。然后调用UnityContainer的Resolve方法,并指定类型实例为 CustomerTasks。由于前面并没有注册该类,UnityContainer 将负责生成一个CustomerTasks 的实例并返回。因为CustomerTasks 类中声明了custructor函数注入ILogger 接口,UnityContainer 将使用先前注册的ILogger 类型,自动实例化ConsoleLogger对象。