


常用的生命周期有瞬时模式,单利模式,每个线程一个对象模式等。
一:TransientLifetimeManager
TransientLifetimeManager模式就是单利模式,是RegisterType注入方式的默认方式
- uc.RegisterType<IUserDAL, UserTwoDAL>(new TransientLifetimeManager());
可以通过hashcode值来看看是否是同一个对象
- public ActionResult Index()
- {
- //获取到容器
- IUnityContainer iuc = MyUnityContainer.GetContainer();
- IUserDAL iud = iuc.Resolve<IUserDAL>();
- IUserDAL iud2 = iuc.Resolve<IUserDAL>();
- //从容器拿到需要的对象
- ViewBag.obj1 = iud.GetHashCode();
- ViewBag.obj2 = iud2.GetHashCode();
-
- return View();
- }
- <div>
- @ViewBag.obj1
- </div>
- <div>
- @ViewBag.obj2
- </div>
可以看到每次输出的hashcode值都不一样说明是瞬时模式
二:TransientLifetimeManager
ContainerControlledLifetimeManager单利模式
容器控制生命周期管理,这个生命周期管理器是RegisterInstance默认使用的生命周期管理器,也就是单件实例,UnityContainer会维护一个对象实例的强引用,每次调用的时候都会返回同一对象.
- uc.RegisterType<IUserDAL, UserTwoDAL>(new ContainerControlledLifetimeManager());
可以看到每次输出的hashcode值都一样说明是单利模式
三:HierarchicalLifetimeManager
分层生命周期管理器,这个管理器类似于ContainerControlledLifetimeManager,也是由UnityContainer来管理,也就是单件实例。不过与ContainerControlledLifetimeManager不 同的是,这个生命周期管理器是分层的,因为Unity的容器时可以嵌套的,所以这个生命周期管理器就是针对这种情况,当使用了这种生命周期管理器,父容器 和子容器所维护的对象的生命周期是由各自的容器来管理
四:PerResolveLifetimeManager
这个生命周期是为了解决循环引用而重复引用的生命周期,先看一下微软官方给出的实例:
- public interface IPresenter
- { }
-
- public class MockPresenter : IPresenter
- {
- public IView View { get; set; }
-
- public MockPresenter(IView view)
- {
- View = view;
- }
- }
-
- public interface IView
- {
- IPresenter Presenter { get; set; }
- }
-
- public class View : IView
- {
- [Dependency]
- public IPresenter Presenter { get; set; }
- }
从这个例子中可以看出,有2个接口IPresenter和IView,还有2个类MockPresenter和View分别实现这2个接口,同时这2个类 中都包含了对另外一个类的对象属性,这个就是一个循环引用,而对应的这个生命周期管理就是针对这种情况而新增的,其类似于 TransientLifetimeManager,但是其不同在于,如果应用了这种生命周期管理器,则在第一调用的时候会创建一个新的对象,而再次通过 循环引用访问到的时候就会返回先前创建的对象实例(单件实例)
五:PerThreadLifetimeManager
每线程生命周期管理器,就是保证每个线程返回同一实例。
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)