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、注册映射
container.RegisterType<IDal,OracleDal>();
RegisterType有以下几个重载方法:
RegisterType<TFrom,TTo>( )
RegisterType<>(LifetimeManagerlifetime)
RegisterType<>(StringnameT)
RegisterType(Typefromtot)
RegisterType<TFrom,TTo>( )
RegisterType<>(LifetimeManagerlifetime)
RegisterType<>(StringnameT)
RegisterType(Typefromtot)
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的实例。
<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(); }
结果:
参考文档:
原文链接:https://www.f2er.com/javaschema/287166.html