Code
/*
作者: mxy1028
演示: 使用unity玩转IOC
编译: csc /reference:Microsoft.Practices.Unity.Configuration.dll,Microsoft.Practices.Unity.dll TEst.cs
依赖: Microsoft.Practices.Unity.dll和Microsoft.Practices.Unity.Configuration.dll
*/
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;
namespace KingRi.Test
{
public interface IDataBase
{
void Save();
}
public class SqlServer : IDataBase
{
public void Save()
{
Console.WriteLine("保存到Sql Server!");
}
}
public class Oracle : IDataBase
{
public void Save()
{
Console.WriteLine("保存到Oracle");
}
}
public class Factory
{
private IDataBase db;
[Dependency]
public IDataBase Db
{
get
{
return db;
}
set
{
this.db = value;
}
}
public void Save()
{
db.Save();
}
public Factory()
{
}
}
public class Client
{
static void Main()
{
//1, 创建容器
IUnityContainer container = new UnityContainer();
//2, 获取配置信息
UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
//3, 使用配置信息设置容器
section.Containers.Default.Configure(container);
//4, 获取对象
Factory obj = container.Resolve<Factory>();
obj.Save();
Console.ReadLine();
}
}
}