Unity 2.0 内置生命周期管理类 Built-In Lifetime Managers

简介:

Unity includes six lifetime managers that you can use directly in your code, but you can create your own lifetime managers to implement specific lifetime scenarios. Unity includes the following lifetime managers:

  • TransientLifetimeManager(每次重新构造新的实例)For this lifetime manager Unity creates and returns a new instance of the requested type for each call to the Resolve or ResolveAll method. This lifetime manager is used by default for all types registered using the RegisterType, method unless you specify a different lifetime manager.
  • ContainerControlledLifetimeManager(单例模式,也是RegisterInstance 方法默认的生命周期) which registers an existing object as a singleton instance. For this lifetime manager Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects. Unity uses this lifetime manager by default for the RegisterInstance method if you do not specify a different lifetime manager. If you want singleton behavior for an object that Unity will create when you specify a type mapping in configuration or when you use the RegisterType method, you must explicitly specify this lifetime manager.

    If you registered a type mapping using configuration or using the RegisterType method, Unity creates a new instance of the registered type during the first call to the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. Subsequent requests return the same instance.

    If you registered an existing instance of an object using the RegisterInstance method, the container returns the same instance for all calls to Resolve or ResolveAll or when the dependency mechanism injects instances into other classes, provided that one of the following is true:

    • You have specified a container-controlled lifetime manager
    • You have used the default lifetime manager
    • You are resolving in the same context in which you registered the instance when using a different lifetime manager.

    Once you have a reference to the proper container, call the RegisterInstance method of that container to register the existing object. Specify as the registration type an interface that the object implements, an object type from which the target object inherits, or the concrete type of the object.

    The following example creates a named (non-default) mapping by specifying the name, Email and uses the default lifetime.

    C#

    myContainer.RegisterInstance<EmailService>("Email", myEmailService);

    Visual Basic

    myContainer.RegisterInstance(Of EmailService)("Email", myEmailService)

    When the container is disposed, it calls the Dispose method of the object and allows it to be garbage collected. Therefore, you must ensure that your code does not maintain a reference to the object.

  • HierarchicalLifetimeManager(分层隔离模式,也就是每层container单独使用单例模式,在一层情况下与ContainerControlledLifetimeManager等同). For this lifetime manager, as for the ContainerControlledLifetimeManager, Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. The distinction is that when there are child containers, each child resolves its own instance of the object and does not share one with the parent. When resolving in the parent, the behavior is like a container controlled lifetime; when resolving the parent and the child you have different instances with each acting as a container-controlled lifetime. If you have multiple children, each will resolve its own instance.

    C#

    IUnityContainer Parent = new UnityContainer();
    IUnityContainer child = Parent.CreateChildContainer();
    
    MyType newInstance = new MyType();
    Parent.RegisterInstance<MyType>(newInstance, new HierarchicalLifetimeManager()); 

    Visual Basic

    Dim Parent As IUnityContainer = New UnityContainer()
    Dim child As IUnityContainer = Parent.CreateChildContainer()
    
    Dim newInstance As New MyType()
    Parent.RegisterInstance(Of MyType)(newInstance, New HierarchicalLifetimeManager())
  • PerResolveLifetimeManager(区别于TransientLifetimeManager在递归构造中会重用已经构造的对象). For this lifetime manager the behavior is like a TransientLifetimeManager, but also provides a signal to the default build plan, marking the type so that instances are reused across the build-up object graph. In the case of recursion, the singleton behavior applies where the object has been registered with the PerResolveLifetimeManager. The following example uses the PerResolveLifetimeManager.

    C#

    public void ViewIsReusedAcrossGraph()
    {
        var container = new UnityContainer()
            .RegisterType<IPresenter, MockPresenter>()
            .RegisterType<IView, View>(new PerResolveLifetimeManager());
        var view = container.Resolve<IView>();
        var realPresenter = (MockPresenter) view.Presenter;
    }

    Visual Basic

    Public Sub ViewIsReusedAcrossGraph()
        Dim container = New UnityContainer() _
            .RegisterType(Of IPresenter, MockPresenter)() _
            .RegisterType(Of IView, View)(New PerResolveLifetimeManager())
        Dim view = container.Resolve(Of IView)()
        Dim realPresenter = DirectCast(view.Presenter, MockPresenter)
    End Sub

    The following small object graph illustrates the per-build behavior for the example. MockPresenter inherits from IPresenter and contains a View and MockPresenter object. IView contains a Presenterobject and View class contains a Presenter dependency. View is reused across the graph per resolve call because View is registered with a PerResolveLifetimeManager.

    C#

    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; }
    }

    Visual Basic

    Public Interface IPresenter
    End Interface
    
    Public Class MockPresenter
        Implements IPresenter
    
        Private _View As IView
        Public Property View() As IView
            Get
                Return _View
            End Get
            Set(ByVal value As IView)
                _View = value
            End Set
        End Property
        
        Public Sub New(ByVal view__1 As IView)
            View = view__1
        End Sub
    End Class
    
    Public Interface IView
        Property Presenter() As IPresenter
    End Interface
    
    Public Class View
        Implements IView
    
        Private _Presenter As IPresenter
        <Dependency()> _ 
        Public Property Presenter() As IPresenter
            Get
                Return _Presenter
            End Get
            Set(ByVal value As IPresenter)
                _Presenter = value
            End Set
        End Property
    
    End Class
  • PerThreadLifetimeManager(故名思议分线程). For this lifetime manager Unity returns, on a per-thread basis, the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects on a per-thread basis. PerThreadLifetimeManager returns different objects from the container for each thread.

    If you registered a type mapping using configuration or using the RegisterType method, Unity creates a new instance of the registered type the first time the type is resolved in a specified thread, either to answer a call to the Resolve or ResolveAll method for the registered type or to fulfill a dependency while resolving a different type. Subsequent resolutions on the same thread return the same instance.

    PerThreadLifetimeManager returns the object desired or permits the container to create a new instance if no such object is currently stored for the current thread. A new instance is also created if called on a thread other than the one that set the value.

     

    When using the PerThreadLifetimeManager, it is recommended that you use RegisterType and do not use RegisterInstance to register an object. 
    When you register an instance with the PerThreadLifetimeManager, the instance is registered only for the executing thread. Calls to Resolve on other threads result in per-thread singletons for container-built instances. If you request a type registered with the PerThreadLifetimeManager in any thread other than the thread it was registered for, the lifetime container for that object finds that there is no registered instance for that thread and, therefore, permits the container to build a new instance for that thread. 
    The result is that for threads other than the one registering the instance, the behavior is the same as if you registered the container lifetime with RegisterType.

    This lifetime manager does not dispose the instances it holds. The thread object is reclaimed by garbage collection when the thread is disposed, but note that the object is not disposed in the sense that the Dispose method is not invoked.

  • ExternallyControlledLifetimeManager()The ExternallyControlledLifetimeManager class provides generic support for externally managed lifetimes. This lifetime manager allows you to register type mappings and existing objects with the container so that it maintains only a weak reference to the objects it creates when you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes based on attributes or constructor parameters within that class. This allows other code to maintain the object in memory or dispose it and enables you to maintain control of the lifetime of existing objects or allow some other mechanism to control the lifetime. Using the ExternallyControlledLifetimeManager enables you to create your own custom lifetime managers for specific scenarios. Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. However, since the container does not hold onto a strong reference to the object after it creates it, the garbage collector can dispose of the object if no other code is holding a strong reference to it.

 

Note:

Using the RegisterInstance method to register an existing object results in the same behavior as if you just registered the lifetime container with RegisterType. Therefore, it is recommended that you do not use the RegisterInstance method to register an existing object when using the non-default lifetime managers except for the thread in which the RegisterInstance was invoked.



本文转自today4king博客园博客,原文链接:http://www.cnblogs.com/jinzhao/archive/2011/08/11/2134582.html,如需转载请自行联系原作者

相关文章
|
4月前
|
图形学 开发者 UED
Unity游戏开发必备技巧:深度解析事件系统运用之道,从生命周期回调到自定义事件,打造高效逻辑与流畅交互的全方位指南
【8月更文挑战第31天】在游戏开发中,事件系统是连接游戏逻辑与用户交互的关键。Unity提供了多种机制处理事件,如MonoBehaviour生命周期回调、事件系统组件及自定义事件。本文介绍如何有效利用这些机制,包括创建自定义事件和使用Unity内置事件系统提升游戏体验。通过合理安排代码执行时机,如在Awake、Start等方法中初始化组件,以及使用委托和事件处理复杂逻辑,可以使游戏更加高效且逻辑清晰。掌握这些技巧有助于开发者更好地应对游戏开发挑战。
177 0
|
5月前
|
图形学 C# 开发者
全面掌握Unity游戏开发核心技术:C#脚本编程从入门到精通——详解生命周期方法、事件处理与面向对象设计,助你打造高效稳定的互动娱乐体验
【8月更文挑战第31天】Unity 是一款强大的游戏开发平台,支持多种编程语言,其中 C# 最为常用。本文介绍 C# 在 Unity 中的应用,涵盖脚本生命周期、常用函数、事件处理及面向对象编程等核心概念。通过具体示例,展示如何编写有效的 C# 脚本,包括 Start、Update 和 LateUpdate 等生命周期方法,以及碰撞检测和类继承等高级技巧,帮助开发者掌握 Unity 脚本编程基础,提升游戏开发效率。
128 0
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏7(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏7(附带项目源码)
97 1
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游9(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游9(附带项目源码)
43 0
|
7月前
|
缓存 图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏8(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏8(附带项目源码)
50 0
|
7月前
|
人工智能 定位技术 图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏6(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏6(附带项目源码)
46 0
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏5(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏5(附带项目源码)
72 0
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏4(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏4(附带项目源码)
52 0
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏3(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏3(附带项目源码)
43 0
|
7月前
|
图形学
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏2(附带项目源码)
【制作100个unity游戏之26】unity2d横版卷轴动作类游戏2(附带项目源码)
49 0