Unity是微软团队开发的一个轻量级,可扩展的依赖注入容器,为松散耦合应用程序提供了很好的解决方案,支持构造器注入,属性注入,方法注入。
同样根据控制反转IOC与依赖注入DI中的例子
interface IDal
{
void save();
}
class SqlServerDal : IDal
{
public void save()
{
Console.WriteLine("SqlServer save.");
}
}
class OracleDal : IDal
{
public void save()
{
Console.WriteLine("Oracle save.");
}
}
Unity的实现如下:
IUnityContainer container = new UnityContainer();
container.RegisterType<IDal, OracleDal>();
var dal = container.Resolve<IDal>();//这是得到OracleDal的实例。
dal.save();
1、创建容器
IUnityContainer container = new UnityContainer();
2、注册映射
a) 代码方式注册映射:
container.RegisterType<IDal, OracleDal>();
RegisterType有以下几个重载方法:
RegisterType<TFrom, TTo>( )
RegisterType<TFrom, TTo>(LifetimeManager lifetime)
RegisterType<TFrom, TTo>(String name)
RegisterType<TFrom, TTo>(String name, LifetimeManager lifetime)
RegisterType<T>(LifetimeManager lifetime)
RegisterType<T>(String name, LifetimeManager lifetime)
RegisterType(Type from, Type to)
RegisterType(Type from, Type to, String name)
RegisterType(Type from, Type to, LifetimeManager lifetime)
RegisterType(Type from, Type to, String name, LifetimeManager lifetime)
RegisterType(Type t, LifetimeManager lifetime)
RegisterType(Type t, String name, LifetimeManager lifetime)
RegisterType<TFrom, TTo>( )
RegisterType<TFrom, TTo>(LifetimeManager lifetime)
RegisterType<TFrom, TTo>(String name)
RegisterType<TFrom, TTo>(String name, LifetimeManager lifetime)
RegisterType<T>(LifetimeManager lifetime)
RegisterType<T>(String name, LifetimeManager lifetime)
RegisterType(Type from, Type to)
RegisterType(Type from, Type to, String name)
RegisterType(Type from, Type to, LifetimeManager lifetime)
RegisterType(Type from, Type to, String name, LifetimeManager lifetime)
RegisterType(Type t, LifetimeManager lifetime)
RegisterType(Type t, String name, LifetimeManager lifetime)
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
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>
<containers>
<container>
<types>
<type
type="UnityDemo.IDal,UnityDemo"
mapTo="UnityDemo.OracleDal,UnityDemo" />
</types>
</container>
</containers>
</unity>
</configuration>
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Configure(container);
var dal = container.Resolve<IDal>();//这是得到OracleDal的实例。
dal.save();
3、获取对象实例
var dal = container.Resolve<IDal>();//这是得到OracleDal的实例。
可以通过方法ResolveAll来得到所有注册对象的实例:
<types>
<type
type="UnityDemo.IDal,UnityDemo" name="oracle"
mapTo="UnityDemo.OracleDal,UnityDemo" />
<type
type="UnityDemo.IDal,UnityDemo" name="sqlserver"
mapTo="UnityDemo.SqlServerDal,UnityDemo" />
</types>
var dals = container.ResolveAll<IDal>();
foreach(IDal dal in dals)
{
dal.save();
}
结果:

参考文档: