注:如类有共有的构造函数而且没有使用Dependency特性,可以在不需要注册映射关系的前提下,使用容器生成实例
1、获取默认映射
IMyService result = myContainer.Resolve<IMyService>();
2、获取命名映射
IMyService result = myContainer.Resolve<IMyService>("Data");
3、获取注册的所有对象
IEnumerable<IMyObject> objects = myContainer.ResolveAll<IMyObject>();
如果没有命名映射将返回Null
foreach (IMyObject foundObject in objects) {
// convert the object reference to the "real" type
MyRealObject theObject = foundObject as MyRealObject;
if (null != theObject)
// work with the object
{
Console.WriteLine(theObject.SomeProperty);
}
}
1.初始化容器,注册
1.1使用XML格式的配置文件,具体参考
http://msdn.microsoft.com/en-us/library/dd203230.aspx
1.2使用UnityContainerll类的RegisterType方法和RegisterInstance方法
1.3 使用容器配置API,踢狗自定义配置
IUnityContainer myContainer = new UnityContainer();
IUnityContainer childCtr = myContainer.CreateChildContainer();
//默认映射
myContainer.RegisterType<IMyService, CustomerService>();
//命名映射
myContainer.RegisterType<IMyService, CustomerService>("Customers");
2.实例生命周期
默认通过容器返回的对象只有一个短暂的生命周期,容器不会存储其引用,每回通过Resolve返回的都是一个新的实例。
通过生命周期管理器管理其生命周期
//类注册为单例
myContainer.RegisterType<IMyService, CustomerService>(new ContainerControlledLifetimeManager());
myContainer.RegisterType<CustomerService>(new ContainerControlledLifetimeManager());
//已存在对象注册为单例
myContainer.RegisterInstance<IMyService>(myEmailService);
注意:注册已存在的对象,不会发生注入,可以通过BuildUp方法强制接口注入和属性注入
使用ExternallyControlledLifetimeManager进行扩展,注册时出入ExternallyControlledLifetimeManager,容器只会保留一个弱引用,可以通过代码去维持对象或者释放对象
注册泛型对象
三种生命周期管理器
1.ContainerControlledLifetimeManager ,RegisterInstance方法的默认管理器
2.ExternallyControlledLifetimeManager
3.PerThreadLifetimeManager
容器层次
容器注销时会注销其所包含的所有的实例
3、Fluent Interface 方法链编程
AddExtension()
Configure
控制反转
依赖注入方式 DI Types(Dependency injection)
接口注入
在接口中定义需要注入的信息。
首先定义一个接口,组件的注入将通过这个接口进行,该接口应由组件提供者提
供,任何想使用该组件的类都必须实现这个接口。
public interface ILog
{
void Log(string message);
}
public interface ILogInject
{
void InjectLog(ILog log);
}
public class client:ILogInject
{
}
抽象工厂模式
将对象间的依赖关系转移到接口上,在调用时由容器来组装
构造函数注入
根据构造函数的类型调用Create方法建立实体对象,然后将对象传给构造函数
降低构造函数与实体对象之间的关联性
属性注入
与构造函数注入基本类似
Unity特点:
1.支持自定义容器
2.对要注入的类型没限制,除了属性注入和方法注入需要【Dependency】特性标注,对类声明没特别要求
3.支持容器层次结构
4.支持配置文件
什么时候使用
1.类或者对象依赖与别的类或者对象
2.依赖关系比较复杂或者需要进一步提前
3.想利用DI
4.想管理对象实例生命周期
5.希望在运行时改变依赖关系
6.希望在Web 应用程序回复时可以缓存或者持久化依赖关系
