博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Unity IOC 生命周期(MVC3.0)【转载】

Posted on 2011-10-04 15:29  itcfj  阅读(505)  评论(0编辑  收藏  举报

Unity IOC 生命周期(MVC3.0)

1:默认不用LifetimeManager

    RegisterType<ICategoryRepository, CategoryRepository>(), 生命周期是每次都会创建一个实例。

2:HttpContext.Item级别的

   RegisterType<ICategoryRepository, CategoryRepository>(new HttpContextLifetimeManager<ICategoryRepository>()),生命周期是 HttpContext.Item级别。就是说

   每一次请求只会创建一个实例。

public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
   {
       public override object GetValue()
       {
           return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
       }
       public override void RemoveValue()
       {
           HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
       }
       public override void SetValue(object newValue)
       {
           HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
       }
       public void Dispose()
       {
           RemoveValue();
       }
   }

3: 容器级别。

  RegisterType<ICategoryRepository, CategoryRepository>(new ContainerControlledLifetimeManager()),这样的生命周期与容器的生命周期一致。