1. unity简介
2.简单的哦入门示例程序
3. 代码下载
1. unity简介
javaee中在很多能够实现IoC模式的框架, unity就是在.net平台上的一种实现。
2.简单的入门示例程序
2.1 新建一个c# console application,添引用:
2.2 新建接口ILogger:
namespace HelloUnity
{
public interface ILogger
{
void Log(String message);
}
}
2.3 新建类SpecialPortSettings:
namespace HelloUnity
{
class SpecialPortSettings
{
public String Port = "8080";
}
}
2.4 新建SpecialLogger类,实现ILogger接口:
namespace HelloUnity.Implementations
{
class SpecialLogger : ILogger
{
public SpecialPortSettings Settings { get; set; }
#region ILogger 成员
public void Log(string message)
{
Console.WriteLine(message);
}
#endregion
}
}
2.5 添加配置文件App.config:
<?
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 ="HelloUnity.ILogger, HelloUnity" />
< namespace name ="HelloUnity.Implementations" />
< assembly name ="HelloUnity" />
< container >
< register type ="ILogger" name ="special" mapTo ="SpecialLogger" >
< property name ="Settings" >
</ property >
</ register >
</ container >
</ unity >
< 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 ="HelloUnity.ILogger, HelloUnity" />
< namespace name ="HelloUnity.Implementations" />
< assembly name ="HelloUnity" />
< container >
< register type ="ILogger" name ="special" mapTo ="SpecialLogger" >
< property name ="Settings" >
</ property >
</ register >
</ container >
</ unity >
</ configuration>
最终的项目工程如下:
2.6 Main测试程序:
namespace HelloUnity
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer().LoadConfiguration();
ILogger specialLogger = container.Resolve<ILogger>("special");
specialLogger.Log("Log");
// 通过unity向specialLogger注入Settings
Console.WriteLine(((SpecialLogger)specialLogger).Settings.Port);
Console.ReadKey();
}
}
}
测试程序首先得到IUnityContainer,这里使用的是默认的配置文件App.config,然后通过Reslove得到specialLogger,最后测试Settings的注入是否成功。
3. 代码下载