Lifestyles

Lifestyle controls in what scope instances are reused,and when to release them(that is do all the necessary clean up steps and then let it go for the Garbage Collector to destroy).

Lifestyle控制实例在什么作用域(scope)内被重用,在什么时候被释放(清理的必要步骤,清理之后被GC回收)

常见的生命方式  Standard Lifestyle :the common ones 

Singleton(default style)

在第一次请求时创建,后续请求重复使用。显示调用释放(container.Release(instance))不起作用。只有当容器释放时才会释放singleton的实例

什么样的类设置为单例呢?

    • 无状态的(State-less)组件。如果有状态的组件为单例,多线程情况下需要保证线程安全
    • 组件的状态很大(object have a big state 理解为对象占用内存多)创建多个实例消耗内存

Transient

每次程序需要时都会创建新的实例

trannsient实例需要释放。

如果是这样获取实例(container.Resolve<MyTransientComponent>()) 需要调用container.Release(myTransientInstance) 释放它

Transient components may be tracked by the container 用完之后如果不是放GC不会回收

不常见的生命方式the less common ones 

Scope

using Castle.MicroKernel.Lifestyle;

using (Container.BeginScope()) //extension method
{
     var one = Container.Resolve<MyScopedComponent>();
     var two = Container.Resolve<MyScopedComponent>();
     Assert.AreSame(one, two);

} // releases the instance

the scope is bound to the CallContext. 注意在多线程情况下子操作应该在scope范围内完成,否则出现空引用错误。

Custom Scope

在一些情况下可能需要“instance per something”,通过实现 IScopeAccessor 接口 实现“instance per your scope

需要实现两个接口IScopeAccessor、ILifetimeScope

AccessorAccessor的生命周期和Container一样长,每个组件(component)有自己的实例

LifetimeScope经常在多个组件之间共享,它的生命期和组件没关系

 

ScopeAccessor的作用:The IScopeAccessor's role is to properly find (and initialize if required) the ILifetimeScope appropriate for given context .

IScopeAccessor是用来查找(有必要的话也初始化)适合给定上下文的 ILifetimeScope

public interface IScopeAccessor : IDisposable
{
ILifetimeScope GetScope(CreationContext context);
}

 

LifetimeScope的作用:实现ILifetimeScope接口的对象的职责是在scope范围内跟踪实例

public interface ILifetimeScope : IDisposable
{
Burden GetCachedInstance(ComponentModel instance, ScopedInstanceActivationCallback createInstance);
}

 

Using(BeginScope)时创建CallContextLifetimeScope 

CallContextLifetimeScope : ILifetimeScope

CallContextLifetimeScope 有一个ScopeCache 里面保存了IDictionary<object,Bruden> 的映射,此映射存储组件对象,保证在范围内reuse

 

Accessor怎么使用的呢?

Bound

posted @ 2019-08-07 23:05  vvf  阅读(372)  评论(0)    收藏  举报