Unity用法(基本对象的创建的两种方法)
RegisterType
假设我们有两个接口ILogger,IStopLightTimer,对这两个接口分别有两个实现,TraceLogger,RealTimeTimer.
The two interfaces are ILogger, which Unity maps to the concrete service class named TraceLogger, and IStoplightTimer, which Unity maps to the concrete service class named RealTimeTimer.
在Unity中我们可以用两种方式来来map接口和实现的关系。
1、代码形式
IUnityContainer container = new UnityContainer()
.RegisterType<ILogger, TraceLogger>()
.RegisterType<IStoplightTimer, RealTimeTimer>();
The mapping registration occurs in the Program file that executes when the application starts.
2、配置文件
在配置文件中添加如下信息:
<container name="containerOne"><types>
<!-- Default (un-named) mapping for ILogger to TraceLogger-->
<type type="ILogger" mapTo="TraceLogger" />
但在代码中应该这样引入:
IUnityContainer myContainer = new UnityContainer();UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers["containerOne"].Configure(myContainer);
以上是得到配置信息。
以上2种方式其实是在Unity中注册一个接口的实现。
通过下面的Resolve方法得到一个TraceLogger实例。
ILogger myLogger = myContainer.Resolve<ILogger>();
posted on 2012-05-20 17:20 malaikuangren 阅读(386) 评论(0) 编辑 收藏 举报