依赖注入容器Unity介绍
Unity是微软团队开发的一个轻量级,可扩展的依赖注入容器,为松散耦合应用程序提供了很好的解决方案,支持构造器注入,属性注入,方法注入。
同样根据控制反转IOC与依赖注入DI中的例子
Unity的实现如下:
1、创建容器
2、注册映射
a) 代码方式注册映射:
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)
3、获取对象实例
可以通过方法ResolveAll来得到所有注册对象的实例:
结果:
参考文档: