Unity的初步使用
1、为什么要要使用Unity
参看:http://www.cnblogs.com/leoo2sk/archive/2009/06/17/1504693.html
2、怎么使用配置文件配置依赖关系
1、安装企业库5.0,下载地址:http://msdn.microsoft.com/en-us/library/ff632023.aspx
2、添加项目引用
System.configuration
Microsoft.Practices.Unity
Microsoft.Practices.Unity.Configuration
public class Container
{
static Container()
{
//UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
Current = new UnityContainer();
try
{
Current.LoadConfiguration("PetShop");
}
catch(Exception ex)
{
throw ex;
}
}
/// <summary>
/// 创建一个子容器
/// </summary>
/// <returns></returns>
public static IUnityContainer CreateChildContainer()
{
return Current.CreateChildContainer();
}
/// <summary>
/// Unity容器<see cref="Microsoft.Practices.Unity.IUnityContainer"/>
/// </summary>
public static IUnityContainer Current
{
get;
private set;
}
}
public interface ILog
{
string GetLog();
}
public class SQLLog:ILog
{
public string GetLog()
{
return "SQLLog";
}
}
public class FileLog:ILog
{
public string GetLog()
{
return "FileLog";
}
}
class Program
{
static void Main(string[] args)
{
ILog logA = Container.Current.Resolve<ILog>();
System.Console.WriteLine(logA.GetLog() + logA.GetHashCode());
ILog logB = Container.Current.Resolve<ILog>();
System.Console.WriteLine(logB.GetLog() + logB.GetHashCode());
System.Console.ReadLine();
}
}