Unity容器中的对象生存期管理

简介:

IoC 容器的对象生存期管理

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

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

LifetimeManager

LifetimeManager 是一个抽象类,其实现了 ILifetimePolicy 接口。该类被作为所有内置或自定义的生存期管理器的父类。它定义了 3 个方法:

  • GetValue - 返回一个已经存储在生存期管理器中对象实例。
  • SetValue - 存储一个新对象实例到生存期管理器中。
  • RemoveValue - 从生存期管理器中将已存储的对象实例删除。UnityContainer 的默认实现将不会调用此方法,但可在定制的容器扩展中调用。

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

  • 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();
    }
复制代码

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();
    }
复制代码

HierarchicalLifetimeManager

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();
    }
复制代码

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();
    }
复制代码

需要注意,在 Debug 模式下,编译器不会优化本地变量,所以引用有可能还存在。而在 Release 模式下会优化。

PerThreadLifetimeManager

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

复制代码
    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();
    }
复制代码

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();
    }
复制代码

完整代码

代码下载









本文转自匠心十年博客园博客,原文链接:http://www.cnblogs.com/gaochundong/archive/2013/04/13/unity_object_lifetime_management.html,如需转载请自行联系原作者

目录
相关文章
|
XML Java 编译器
如何使用IOC容器进行对象的管理和创建?
如何使用IOC容器进行对象的管理和创建?
233 0
如何使用IOC容器进行对象的管理和创建?
|
Cloud Native 测试技术 持续交付
Docker Compose 解析:定义和管理多容器应用,从多角度探索其优势和应用场景
Docker Compose 解析:定义和管理多容器应用,从多角度探索其优势和应用场景
625 0
|
存储 设计模式 监控
运用Unity Profiler定位内存泄漏并实施对象池管理优化内存使用
【7月更文第10天】在Unity游戏开发中,内存管理是至关重要的一个环节。内存泄漏不仅会导致游戏运行缓慢、卡顿,严重时甚至会引发崩溃。Unity Profiler作为一个强大的性能分析工具,能够帮助开发者深入理解应用程序的内存使用情况,从而定位并解决内存泄漏问题。同时,通过实施对象池管理策略,可以显著优化内存使用,提高游戏性能。本文将结合代码示例,详细介绍如何利用Unity Profiler定位内存泄漏,并实施对象池来优化内存使用。
1430 0
|
设计模式 存储 人工智能
深度解析Unity游戏开发:从零构建可扩展与可维护的游戏架构,让你的游戏项目在模块化设计、脚本对象运用及状态模式处理中焕发新生,实现高效迭代与团队协作的完美平衡之路
【9月更文挑战第1天】游戏开发中的架构设计是项目成功的关键。良好的架构能提升开发效率并确保项目的长期可维护性和可扩展性。在使用Unity引擎时,合理的架构尤为重要。本文探讨了如何在Unity中实现可扩展且易维护的游戏架构,包括模块化设计、使用脚本对象管理数据、应用设计模式(如状态模式)及采用MVC/MVVM架构模式。通过这些方法,可以显著提高开发效率和游戏质量。例如,模块化设计将游戏拆分为独立模块。
903 3
|
存储 Linux 应用服务中间件
容器卷管理
容器卷管理
144 2
|
安全 关系型数据库 开发者
Docker Compose凭借其简单易用的特性,已经成为开发者在构建和管理多容器应用时不可或缺的工具。
Docker Compose是容器编排利器,简化多容器应用管理。通过YAML文件定义服务、网络和卷,一键启动应用环境。核心概念包括服务(组件集合)、网络(灵活通信)、卷(数据持久化)。实战中,编写docker-compose.yml,如设置Nginx和Postgres服务,用`docker-compose up -d`启动。高级特性涉及依赖、环境变量、健康检查和数据持久化。最佳实践涵盖环境隔离、CI/CD、资源管理和安全措施。案例分析展示如何构建微服务应用栈,实现一键部署。Docker Compose助力开发者高效驾驭复杂容器场景。
247 1
|
Java 数据库连接 Docker
【Docker 专栏】Docker 容器内环境变量的管理与使用
【5月更文挑战第9天】本文介绍了Docker容器中环境变量的管理与使用,环境变量用于传递配置信息和设置应用运行环境。设置方法包括在Dockerfile中使用`ENV`指令或在启动容器时通过`-e`参数设定。应用可直接访问环境变量或在脚本中使用。环境变量作用包括传递配置、设置运行环境和动态调整应用行为。使用时注意变量名称和值的合法性、保密性和覆盖问题。理解并熟练运用环境变量能提升Docker技术的使用效率和软件部署质量。
1112 0
【Docker 专栏】Docker 容器内环境变量的管理与使用
|
存储 图形学
【unity小技巧】unity事件系统创建通用的对象交互的功能
【unity小技巧】unity事件系统创建通用的对象交互的功能
365 0
|
前端开发 Java 容器
家族传承:Spring MVC中父子容器的搭建与管理指南
家族传承:Spring MVC中父子容器的搭建与管理指南
269 3
|
存储 Linux 文件存储
Linux使用Docker部署Traefik容器并实现远程访问管理界面-1
Linux使用Docker部署Traefik容器并实现远程访问管理界面
520 0