Unity(2)生命周期

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

posted @ 2009-05-26 11:00  TG.Yang's IT Space  阅读(523)  评论(0编辑  收藏  举报