用于UserStore的每个HttpRequest的Unity IoC Lifetime

时间:2014-04-06 12:58:49

标签: c# dependency-injection unity-container asp.net-mvc-5 asp.net-identity

我正在尝试清理新MVC5 / Owin安全实现中开箱即用的AccountController.cs的默认实现。我修改了我的构造函数,看起来像这样:

private UserManager<ApplicationUser> UserManager;
public AccountController(UserManager<ApplicationUser> userManager)
{
    this.UserManager = userManager;
}

另外,我为Unity创建了一个生命周期管理器,如下所示:

 public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
    {
        private HttpContextBase _context = null;
        public HttpContextLifetimeManager()
        {
            _context = new HttpContextWrapper(HttpContext.Current);
        }
        public HttpContextLifetimeManager(HttpContextBase context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            _context = context;
        }
        public void Dispose()
        {
            this.RemoveValue();
        }
        public override object GetValue()
        {
            return _context.Items[typeof(T)];
        }
        public override void RemoveValue()
        {
            _context.Items.Remove(typeof(T));
        }
        public override void SetValue(object newValue)
        {
            _context.Items[typeof(T)] = newValue;
        }
    }

我不确定如何在UnityConfig.cs中写这个,但这是我到目前为止所做的:

container.RegisterType<UserManager<ApplicationUser>>(new HttpContextLifetimeManager(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new RecipeManagerContext()))));

我确实找到了另一个例子(使用AutoFac)这样做:

container.Register(c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>( new RecipeManagerContext())))
                .As<UserManager<ApplicationUser>>().InstancePerHttpRequest();

如何使用Unity IoC生命周期管理翻译上述语句?

1 个答案:

答案 0 :(得分:4)

UserManager在特定生命周期内注册的方法是正确的。但是,我不理解为什么它甚至会编译,因为您的HttpContextLifetimeManager期望HttpContext作为参数。

另一个问题是您的实施是错误的。无参数构造函数采用当前 http上下文,但是您希望生命周期管理器使用实例创建的上下文,而不是类型为已注册的 强>上。如果使用无参数构造函数,则可能导致http上下文不匹配问题。

首先,将您的实施更改为

public class HttpContextLifetimeManager : LifetimeManager
{
 private readonly object key = new object();

 public override object GetValue()
 {
     if (HttpContext.Current != null && 
         HttpContext.Current.Items.Contains(key))
         return HttpContext.Current.Items[key];
     else
         return null;
 }

 public override void RemoveValue()
 {
     if (HttpContext.Current != null)
         HttpContext.Current.Items.Remove(key);
 }

 public override void SetValue(object newValue)
 {
     if (HttpContext.Current != null)
         HttpContext.Current.Items[key] = newValue;
 }
}

然后注册您的类型

container.RegisterType<UserManager<ApplicationUser>>( new HttpContextLifetimeManager() );