现在的位置: 首页 > 综合 > 正文

Unity IOC 生命周期(MVC3.0)

2012年01月25日 ⁄ 综合 ⁄ 共 802字 ⁄ 字号 评论关闭

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()),这样的生命周期与容器的生命周期一致。

抱歉!评论已关闭.