溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Unity容器中對對象的生存期進行管理

發布時間:2021-01-28 09:25:26 來源:億速云 閱讀:222 作者:Leah 欄目:開發技術

本篇文章為大家展示了怎么在Unity容器中對對象的生存期進行管理,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

IoC容器的對象生存期管理

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

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過程中是可被重用的。
Code Double

復制代碼 代碼如下:


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默認的生存期管理器。其內部的實現都為空,這就意味著每次容器都會創建和返回一個新的對象實例,當然容器也不負責存儲和銷毀該對象實例。

復制代碼 代碼如下:


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.Resolve<IExample>().SayHello();
        example = container.Resolve<IExample>();
      }
      // container is disposed but Example instance still lives
      // all previously created instances weren't disposed!
      example.SayHello();

      Console.ReadKey();
    }

怎么在Unity容器中對對象的生存期進行管理

ContainerControlledLifetimeManager

ContainerControlledLifetimeManager將為UnityContainer及其子容器提供一個Singleton的注冊類型對象實例。其只在第一次請求某注冊類型時創建一個新的對象實例,該對象實例將被存儲到生存期管理器中,并且一直被重用。當容器析構時,生存期管理器會調用RemoveValue將存儲的對象銷毀。

Singleton對象實例對應每個對象類型注冊,如果同一對象類型注冊多次,則將為每次注冊創建單一的實例。

復制代碼 代碼如下:


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.Resolve<IExample>().SayHello();

          // run one resolving in other thread and still receive same instance
          Thread thread = new Thread(
            () => 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 - instance has been disposed with container
        example.SayHello();
      }
      catch (ObjectDisposedException ex)
      {
        Console.WriteLine(ex.Message);
      }

      Console.ReadKey();
    }

怎么在Unity容器中對對象的生存期進行管理

HierarchicalLifetimeManager類衍生自ContainerControlledLifetimeManager,其繼承了父類的所有行為。與父類的不同之處在于子容器中的生存期管理器行為。ContainerControlledLifetimeManager共享相同的對象實例,包括在子容器中。而HierarchicalLifetimeManager只在同一個容器內共享,每個子容器都有其單獨的對象實例。

復制代碼 代碼如下:


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.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 - instance has been disposed with container
        example.SayHello();
      }
      catch (ObjectDisposedException ex)
      {
        Console.WriteLine(ex.Message);
      }

      Console.ReadKey();
    }

怎么在Unity容器中對對象的生存期進行管理

ExternallyControlledLifetimeManager

ExternallyControlledLifetimeManager中的對象實例的生存期限將有UnityContainer外部的實現控制。此生存期管理器內部直存儲了所提供對象實例的一個WeakReference。所以如果UnityContainer容器外部實現中沒有對該對象實例的強引用,則該對象實例將被GC回收。再次請求該對象類型實例時,將會創建新的對象實例。

復制代碼 代碼如下:


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.Resolve<IExample>().SayHello();
        container.Resolve<IExample>().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.Resolve<IExample>().SayHello();
        example = container.Resolve<IExample>();
      }

      example.SayHello();

      Console.ReadKey();
    }

這個結果證明強引用還存在,不知道為什么?如果你找到了原因,煩請告訴我,謝謝。

怎么在Unity容器中對對象的生存期進行管理

PerThreadLifetimeManager

PerThreadLifetimeManager模型提供“每線程單實例”功能。所有的對象實例在內部被存儲在ThreadStatic的集合。容器并不跟蹤對象實例的創建并且也不負責Dipose。

復制代碼 代碼如下:


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

        Action<int> action = delegate(int sleep)
        {
          // both calls use same instance per thread
          container.Resolve<IExample>().SayHello();
          Thread.Sleep(sleep);
          container.Resolve<IExample>().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.Resolve<IExample>();
      }

      example.SayHello();

      Console.ReadKey();
    }

怎么在Unity容器中對對象的生存期進行管理

PerResolveLifetimeManager

PerResolveLifetimeManager是Unity內置的一個特殊的模型。因為Unity使用單獨的邏輯來處理注冊類型的Per-Resolve生命期。每次請求Resolve一個類型對象時,UnityContainer都會創建并返回一個新的對象實例。

復制代碼 代碼如下:


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

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

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

      example.SayHello();

      Console.ReadKey();
    }

怎么在Unity容器中對對象的生存期進行管理

上述內容就是怎么在Unity容器中對對象的生存期進行管理,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女