通过使用unity容器,从配置文件里读取配置,解析出一个接口的实现,或在程序里指定一个接口的实现:
1、先建一个项目,名字为ClassLibrary,里面有ILogger.cs Logger.cs
Logger.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using System.Text;
namespace ClassLibrary
{
public class TextLogger : ILogger
{
public void Log(string str)
{
Console.WriteLine(str + ":TextLogger.Log()");
}
}
public class DBLogger : ILogger
{
public void Log(string str)
{
Console.WriteLine(str + ":DBLogger.Log()");
}
}
}
ILogger.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary
{
public interface ILogger
{
void Log(string str);
}
}
Main.cs:
public static void Main()
{
IUnityContainer c = new UnityContainer();
c.LoadConfiguration();
c.Resolve<ILogger>().Log("abbbbb");//从默认注册里取,见配置文件的Container>>Register节点
c.Resolve<ILogger>("special").Log("abbbbb");//从name为special的注册里取,见配置文件的Container>>Register节点
return;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<ILogger, TextLogger>();
container.RegisterType<ILogger, TextLogger>("text");
container.RegisterType<ILogger, DBLogger>("db");
container.Resolve<ILogger>().Log("abc");
IEnumerable<ILogger> i = container.ResolveAll<ILogger>();
foreach (ILogger l in i) {
l.Log("lllll");
}
}
}
配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="ILogger" type="ClassLibrary.ILogger, ClassLibrary" /><!--这一行可选,可不要-->
<namespace name="ClassLibrary" />
<assembly name="ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<container>
<register type="ILogger" mapTo="DBLogger" />
<register type="ILogger" name="special" mapTo="TextLogger" />
</container>
</unity>
</configuration>