主頁(yè) > 知識(shí)庫(kù) > 基于Unity容器中的對(duì)象生存期管理分析

基于Unity容器中的對(duì)象生存期管理分析

熱門(mén)標(biāo)簽:電子圍欄 Linux服務(wù)器 科大訊飛語(yǔ)音識(shí)別系統(tǒng) 團(tuán)購(gòu)網(wǎng)站 銀行業(yè)務(wù) 阿里云 服務(wù)器配置 Mysql連接數(shù)設(shè)置

IoC容器的對(duì)象生存期管理

如果你一直在使用IoC容器,你可能已經(jīng)使用過(guò)了一些對(duì)象生存期管理模型(Object Lifetime Management)。通過(guò)對(duì)對(duì)象生存期的管理,將使對(duì)象的復(fù)用成為可能。同時(shí)其使容器可以控制如何創(chuàng)建和管理對(duì)象實(shí)例。

Unity提供的對(duì)象生存期管理模型是通過(guò)從抽象類(lèi)LifetimeManager的派生類(lèi)來(lái)完成。Unity將為每個(gè)類(lèi)型的注冊(cè)創(chuàng)建生存期管理器。每當(dāng)UnityContainer需要?jiǎng)?chuàng)建一個(gè)新的對(duì)象實(shí)例時(shí),將首先檢測(cè)該對(duì)象類(lèi)型的生存期管理器,是否已有一個(gè)對(duì)象實(shí)例可用。如果沒(méi)有對(duì)象實(shí)例可用,則UnityContainer將基于配置的信息構(gòu)造該對(duì)象實(shí)例并將該對(duì)象交予對(duì)象生存期管理器。

LifetimeManager

LifetimeManager是一個(gè)抽象類(lèi),其實(shí)現(xiàn)了ILifetimePolicy接口。該類(lèi)被作為所有內(nèi)置或自定義的生存期管理器的父類(lèi)。它定義了3個(gè)方法: GetValue - 返回一個(gè)已經(jīng)存儲(chǔ)在生存期管理器中對(duì)象實(shí)例。 SetValue - 存儲(chǔ)一個(gè)新對(duì)象實(shí)例到生存期管理器中。 RemoveValue - 從生存期管理器中將已存儲(chǔ)的對(duì)象實(shí)例刪除。UnityContainer的默認(rèn)實(shí)現(xiàn)將不會(huì)調(diào)用此方法,但可在定制的容器擴(kuò)展中調(diào)用。

Unity內(nèi)置了6種生存期管理模型,其中有2種即負(fù)責(zé)對(duì)象實(shí)例的創(chuàng)建也負(fù)責(zé)對(duì)象實(shí)例的銷(xiāo)毀(Disposing)。

•TransientLifetimeManager - 為每次請(qǐng)求生成新的類(lèi)型對(duì)象實(shí)例。 (默認(rèn)行為)
•ContainerControlledLifetimeManager - 實(shí)現(xiàn)Singleton對(duì)象實(shí)例。 當(dāng)容器被Disposed后,對(duì)象實(shí)例也被Disposed。
•HierarchicalifetimeManager - 實(shí)現(xiàn)Singleton對(duì)象實(shí)例。但子容器并不共享父容器實(shí)例,而是創(chuàng)建針對(duì)字容器的Singleton對(duì)象實(shí)例。當(dāng)容器被Disposed后,對(duì)象實(shí)例也被Disposed。
•ExternallyControlledLifetimeManager - 實(shí)現(xiàn)Singleton對(duì)象實(shí)例,但容器僅持有該對(duì)象的弱引用(WeakReference),所以該對(duì)象的生存期由外部引用控制。
•PerThreadLifetimeManager - 為每個(gè)線(xiàn)程生成Singleton的對(duì)象實(shí)例,通過(guò)ThreadStatic實(shí)現(xiàn)。
•PerResolveLifetimeManager - 實(shí)現(xiàn)與TransientLifetimeManager類(lèi)似的行為,為每次請(qǐng)求生成新的類(lèi)型對(duì)象實(shí)例。不同之處在于對(duì)象實(shí)例在BuildUp過(guò)程中是可被重用的。
Code Double

復(fù)制代碼 代碼如下:

public interface IExample : IDisposable
    {
      void SayHello();
    }

    public class Example : IExample
    {
      private bool _disposed = false;
      private readonly Guid _key = Guid.NewGuid();

      public void SayHello()
      {
        if (_disposed)
        {
          throw new ObjectDisposedException("Example",
              string.Format("{0} is already disposed!", _key));
        }

        Console.WriteLine("{0} says hello in thread {1}!", _key,
            Thread.CurrentThread.ManagedThreadId);
      }

      public void Dispose()
      {
        if (!_disposed)
        {
          _disposed = true;
        }
      }
    }


TransientLifetimeManager

TransientLifetimeManager是Unity默認(rèn)的生存期管理器。其內(nèi)部的實(shí)現(xiàn)都為空,這就意味著每次容器都會(huì)創(chuàng)建和返回一個(gè)新的對(duì)象實(shí)例,當(dāng)然容器也不負(fù)責(zé)存儲(chǔ)和銷(xiāo)毀該對(duì)象實(shí)例。

復(fù)制代碼 代碼如下:

private static void TestTransientLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new TransientLifetimeManager());

        // each one gets its own instance
        container.ResolveIExample>().SayHello();
        example = container.ResolveIExample>();
      }
      // container is disposed but Example instance still lives
      // all previously created instances weren't disposed!
      example.SayHello();

      Console.ReadKey();
    }

ContainerControlledLifetimeManager

ContainerControlledLifetimeManager將為UnityContainer及其子容器提供一個(gè)Singleton的注冊(cè)類(lèi)型對(duì)象實(shí)例。其只在第一次請(qǐng)求某注冊(cè)類(lèi)型時(shí)創(chuàng)建一個(gè)新的對(duì)象實(shí)例,該對(duì)象實(shí)例將被存儲(chǔ)到生存期管理器中,并且一直被重用。當(dāng)容器析構(gòu)時(shí),生存期管理器會(huì)調(diào)用RemoveValue將存儲(chǔ)的對(duì)象銷(xiāo)毀。

Singleton對(duì)象實(shí)例對(duì)應(yīng)每個(gè)對(duì)象類(lèi)型注冊(cè),如果同一對(duì)象類(lèi)型注冊(cè)多次,則將為每次注冊(cè)創(chuàng)建單一的實(shí)例。

復(fù)制代碼 代碼如下:

private static void TestContainerControlledLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new ContainerControlledLifetimeManager());

        IUnityContainer firstSub = null;
        IUnityContainer secondSub = null;

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

          // all containers share same instance
          // each resolve returns same instance
          firstSub.ResolveIExample>().SayHello();

          // run one resolving in other thread and still receive same instance
          Thread thread = new Thread(
            () => secondSub.ResolveIExample>().SayHello());
          thread.Start();

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

      try
      {
        // exception - instance has been disposed with container
        example.SayHello();
      }
      catch (ObjectDisposedException ex)
      {
        Console.WriteLine(ex.Message);
      }

      Console.ReadKey();
    }

HierarchicalLifetimeManager類(lèi)衍生自ContainerControlledLifetimeManager,其繼承了父類(lèi)的所有行為。與父類(lèi)的不同之處在于子容器中的生存期管理器行為。ContainerControlledLifetimeManager共享相同的對(duì)象實(shí)例,包括在子容器中。而HierarchicalLifetimeManager只在同一個(gè)容器內(nèi)共享,每個(gè)子容器都有其單獨(dú)的對(duì)象實(shí)例。

復(fù)制代碼 代碼如下:

private static void TestHierarchicalLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new HierarchicalLifetimeManager());

        IUnityContainer firstSub = null;
        IUnityContainer secondSub = null;

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

          // each subcontainer has its own instance
          firstSub.ResolveIExample>().SayHello();
          secondSub.ResolveIExample>().SayHello();
          container.ResolveIExample>().SayHello();
          example = firstSub.ResolveIExample>();
        }
        finally
        {
          if (firstSub != null) firstSub.Dispose();
          if (secondSub != null) secondSub.Dispose();
        }
      }

      try
      {
        // exception - instance has been disposed with container
        example.SayHello();
      }
      catch (ObjectDisposedException ex)
      {
        Console.WriteLine(ex.Message);
      }

      Console.ReadKey();
    }

ExternallyControlledLifetimeManager

ExternallyControlledLifetimeManager中的對(duì)象實(shí)例的生存期限將有UnityContainer外部的實(shí)現(xiàn)控制。此生存期管理器內(nèi)部直存儲(chǔ)了所提供對(duì)象實(shí)例的一個(gè)WeakReference。所以如果UnityContainer容器外部實(shí)現(xiàn)中沒(méi)有對(duì)該對(duì)象實(shí)例的強(qiáng)引用,則該對(duì)象實(shí)例將被GC回收。再次請(qǐng)求該對(duì)象類(lèi)型實(shí)例時(shí),將會(huì)創(chuàng)建新的對(duì)象實(shí)例。

復(fù)制代碼 代碼如下:

private static void TestExternallyControlledLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new ExternallyControlledLifetimeManager());

        // same instance is used in following
        container.ResolveIExample>().SayHello();
        container.ResolveIExample>().SayHello();

        // run garbate collector. Stored Example instance will be released
        // beacuse there is no reference for it and LifetimeManager holds
        // only WeakReference       
        GC.Collect();

        // object stored targeted by WeakReference was released
        // new instance is created!
        container.ResolveIExample>().SayHello();
        example = container.ResolveIExample>();
      }

      example.SayHello();

      Console.ReadKey();
    }


這個(gè)結(jié)果證明強(qiáng)引用還存在,不知道為什么?如果你找到了原因,煩請(qǐng)告訴我,謝謝。

PerThreadLifetimeManager

PerThreadLifetimeManager模型提供“每線(xiàn)程單實(shí)例”功能。所有的對(duì)象實(shí)例在內(nèi)部被存儲(chǔ)在ThreadStatic的集合。容器并不跟蹤對(duì)象實(shí)例的創(chuàng)建并且也不負(fù)責(zé)Dipose。

復(fù)制代碼 代碼如下:

private static void TestPerThreadLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new PerThreadLifetimeManager());

        Actionint> action = delegate(int sleep)
        {
          // both calls use same instance per thread
          container.ResolveIExample>().SayHello();
          Thread.Sleep(sleep);
          container.ResolveIExample>().SayHello();
        };

        Thread thread1 = new Thread((a) => action.Invoke((int)a));
        Thread thread2 = new Thread((a) => action.Invoke((int)a));
        thread1.Start(50);
        thread2.Start(50);

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

        example = container.ResolveIExample>();
      }

      example.SayHello();

      Console.ReadKey();
    }

PerResolveLifetimeManager

PerResolveLifetimeManager是Unity內(nèi)置的一個(gè)特殊的模型。因?yàn)閁nity使用單獨(dú)的邏輯來(lái)處理注冊(cè)類(lèi)型的Per-Resolve生命期。每次請(qǐng)求Resolve一個(gè)類(lèi)型對(duì)象時(shí),UnityContainer都會(huì)創(chuàng)建并返回一個(gè)新的對(duì)象實(shí)例。

復(fù)制代碼 代碼如下:

private static void TestPerResolveLifetimeManager()
    {
      IExample example;
      using (IUnityContainer container = new UnityContainer())
      {
        container.RegisterType(typeof(IExample), typeof(Example),
          new PerResolveLifetimeManager());

        container.ResolveIExample>().SayHello();
        container.ResolveIExample>().SayHello();

        example = container.ResolveIExample>();
      }

      example.SayHello();

      Console.ReadKey();
    }

您可能感興趣的文章:
  • C#使用Protocol Buffer(ProtoBuf)進(jìn)行Unity中的Socket通信
  • unity實(shí)現(xiàn)攝像頭跟隨
  • Unity UGUI教程之實(shí)現(xiàn)滑頁(yè)效果
  • 在Unity中實(shí)現(xiàn)動(dòng)畫(huà)的正反播放代碼
  • C#在Unity游戲開(kāi)發(fā)中進(jìn)行多線(xiàn)程編程的方法
  • Unity移動(dòng)端的復(fù)制要這么寫(xiě)示例代碼

標(biāo)簽:棗莊 衢州 衡水 江蘇 廣元 大理 蚌埠 萍鄉(xiāng)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《基于Unity容器中的對(duì)象生存期管理分析》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話(huà)咨詢(xún)

    • 400-1100-266