zl程序教程

您现在的位置是:首页 >  工具

当前栏目

基于Unity容器中的对象生存期管理分析

容器对象 管理 分析 基于 Unity 生存期
2023-06-13 09:14:50 时间

IoC容器的对象生存期管理

如果你一直在使用IoC容器,你可能已经使用过了一些对象生存期管理模型(ObjectLifetimeManagement)。通过对对象生存期的管理,将使对象的复用成为可能。同时其使容器可以控制如何创建和管理对象实例。

Unity提供的对象生存期管理模型是通过从抽象类LifetimeManager的派生类来完成。Unity将为每个类型的注册创建生存期管理器。每当UnityContainer需要创建一个新的对象实例时,将首先检测该对象类型的生存期管理器,是否已有一个对象实例可用。如果没有对象实例可用,则UnityContainer将基于配置的信息构造该对象实例并将该对象交予对象生存期管理器。

LifetimeManager

LifetimeManager是一个抽象类,其实现了ILifetimePolicy接口。该类被作为所有内置或自定义的生存期管理器的父类。它定义了3个方法:GetValue-返回一个已经存储在生存期管理器中对象实例。SetValue-存储一个新对象实例到生存期管理器中。RemoveValue-从生存期管理器中将已存储的对象实例删除。UnityContainer的默认实现将不会调用此方法,但可在定制的容器扩展中调用。

Unity内置了6种生存期管理模型,其中有2种即负责对象实例的创建也负责对象实例的销毁(Disposing)。

•TransientLifetimeManager-为每次请求生成新的类型对象实例。(默认行为)
•ContainerControlledLifetimeManager-实现Singleton对象实例。当容器被Disposed后,对象实例也被Disposed。
•HierarchicalifetimeManager-实现Singleton对象实例。但子容器并不共享父容器实例,而是创建针对字容器的Singleton对象实例。当容器被Disposed后,对象实例也被Disposed。
•ExternallyControlledLifetimeManager-实现Singleton对象实例,但容器仅持有该对象的弱引用(WeakReference),所以该对象的生存期由外部引用控制。
•PerThreadLifetimeManager-为每个线程生成Singleton的对象实例,通过ThreadStatic实现。
•PerResolveLifetimeManager-实现与TransientLifetimeManager类似的行为,为每次请求生成新的类型对象实例。不同之处在于对象实例在BuildUp过程中是可被重用的。
CodeDouble

复制代码代码如下:

publicinterfaceIExample:IDisposable
   {
     voidSayHello();
   }

   publicclassExample:IExample
   {
     privatebool_disposed=false;
     privatereadonlyGuid_key=Guid.NewGuid();

     publicvoidSayHello()
     {
       if(_disposed)
       {
         thrownewObjectDisposedException("Example",
             string.Format("{0}isalreadydisposed!",_key));
       }

       Console.WriteLine("{0}sayshellointhread{1}!",_key,
           Thread.CurrentThread.ManagedThreadId);
     }

     publicvoidDispose()
     {
       if(!_disposed)
       {
         _disposed=true;
       }
     }
   }


TransientLifetimeManager

TransientLifetimeManager是Unity默认的生存期管理器。其内部的实现都为空,这就意味着每次容器都会创建和返回一个新的对象实例,当然容器也不负责存储和销毁该对象实例。

复制代码代码如下:

privatestaticvoidTestTransientLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newTransientLifetimeManager());

       //eachonegetsitsowninstance
       container.Resolve<IExample>().SayHello();
       example=container.Resolve<IExample>();
     }
     //containerisdisposedbutExampleinstancestilllives
     //allpreviouslycreatedinstancesweren"tdisposed!
     example.SayHello();

     Console.ReadKey();
   }

ContainerControlledLifetimeManager

ContainerControlledLifetimeManager将为UnityContainer及其子容器提供一个Singleton的注册类型对象实例。其只在第一次请求某注册类型时创建一个新的对象实例,该对象实例将被存储到生存期管理器中,并且一直被重用。当容器析构时,生存期管理器会调用RemoveValue将存储的对象销毁。

Singleton对象实例对应每个对象类型注册,如果同一对象类型注册多次,则将为每次注册创建单一的实例。

复制代码代码如下:
privatestaticvoidTestContainerControlledLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newContainerControlledLifetimeManager());

       IUnityContainerfirstSub=null;
       IUnityContainersecondSub=null;

       try
       {
         firstSub=container.CreateChildContainer();
         secondSub=container.CreateChildContainer();

         //allcontainerssharesameinstance
         //eachresolvereturnssameinstance
         firstSub.Resolve<IExample>().SayHello();

         //runoneresolvinginotherthreadandstillreceivesameinstance
         Threadthread=newThread(
           ()=>secondSub.Resolve<IExample>().SayHello());
         thread.Start();

         container.Resolve<IExample>().SayHello();
         example=container.Resolve<IExample>();
         thread.Join();
       }
       finally
       {
         if(firstSub!=null)firstSub.Dispose();
         if(secondSub!=null)secondSub.Dispose();
       }
     }

     try
     {
       //exception-instancehasbeendisposedwithcontainer
       example.SayHello();
     }
     catch(ObjectDisposedExceptionex)
     {
       Console.WriteLine(ex.Message);
     }

     Console.ReadKey();
   }

HierarchicalLifetimeManager类衍生自ContainerControlledLifetimeManager,其继承了父类的所有行为。与父类的不同之处在于子容器中的生存期管理器行为。ContainerControlledLifetimeManager共享相同的对象实例,包括在子容器中。而HierarchicalLifetimeManager只在同一个容器内共享,每个子容器都有其单独的对象实例。

复制代码代码如下:
privatestaticvoidTestHierarchicalLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newHierarchicalLifetimeManager());

       IUnityContainerfirstSub=null;
       IUnityContainersecondSub=null;

       try
       {
         firstSub=container.CreateChildContainer();
         secondSub=container.CreateChildContainer();

         //eachsubcontainerhasitsowninstance
         firstSub.Resolve<IExample>().SayHello();
         secondSub.Resolve<IExample>().SayHello();
         container.Resolve<IExample>().SayHello();
         example=firstSub.Resolve<IExample>();
       }
       finally
       {
         if(firstSub!=null)firstSub.Dispose();
         if(secondSub!=null)secondSub.Dispose();
       }
     }

     try
     {
       //exception-instancehasbeendisposedwithcontainer
       example.SayHello();
     }
     catch(ObjectDisposedExceptionex)
     {
       Console.WriteLine(ex.Message);
     }

     Console.ReadKey();
   }

ExternallyControlledLifetimeManager

ExternallyControlledLifetimeManager中的对象实例的生存期限将有UnityContainer外部的实现控制。此生存期管理器内部直存储了所提供对象实例的一个WeakReference。所以如果UnityContainer容器外部实现中没有对该对象实例的强引用,则该对象实例将被GC回收。再次请求该对象类型实例时,将会创建新的对象实例。

复制代码代码如下:
privatestaticvoidTestExternallyControlledLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newExternallyControlledLifetimeManager());

       //sameinstanceisusedinfollowing
       container.Resolve<IExample>().SayHello();
       container.Resolve<IExample>().SayHello();

       //rungarbatecollector.StoredExampleinstancewillbereleased
       //beacusethereisnoreferenceforitandLifetimeManagerholds
       //onlyWeakReference       
       GC.Collect();

       //objectstoredtargetedbyWeakReferencewasreleased
       //newinstanceiscreated!
       container.Resolve<IExample>().SayHello();
       example=container.Resolve<IExample>();
     }

     example.SayHello();

     Console.ReadKey();
   }


这个结果证明强引用还存在,不知道为什么?如果你找到了原因,烦请告诉我,谢谢。

PerThreadLifetimeManager

PerThreadLifetimeManager模型提供“每线程单实例”功能。所有的对象实例在内部被存储在ThreadStatic的集合。容器并不跟踪对象实例的创建并且也不负责Dipose。

复制代码代码如下:
privatestaticvoidTestPerThreadLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newPerThreadLifetimeManager());

       Action<int>action=delegate(intsleep)
       {
         //bothcallsusesameinstanceperthread
         container.Resolve<IExample>().SayHello();
         Thread.Sleep(sleep);
         container.Resolve<IExample>().SayHello();
       };

       Threadthread1=newThread((a)=>action.Invoke((int)a));
       Threadthread2=newThread((a)=>action.Invoke((int)a));
       thread1.Start(50);
       thread2.Start(50);

       thread1.Join();
       thread2.Join();

       example=container.Resolve<IExample>();
     }

     example.SayHello();

     Console.ReadKey();
   }

PerResolveLifetimeManager

PerResolveLifetimeManager是Unity内置的一个特殊的模型。因为Unity使用单独的逻辑来处理注册类型的Per-Resolve生命期。每次请求Resolve一个类型对象时,UnityContainer都会创建并返回一个新的对象实例。

复制代码代码如下:
privatestaticvoidTestPerResolveLifetimeManager()
   {
     IExampleexample;
     using(IUnityContainercontainer=newUnityContainer())
     {
       container.RegisterType(typeof(IExample),typeof(Example),
         newPerResolveLifetimeManager());

       container.Resolve<IExample>().SayHello();
       container.Resolve<IExample>().SayHello();

       example=container.Resolve<IExample>();
     }

     example.SayHello();

     Console.ReadKey();
   }