我正在尝试清理新的 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 生命周期管理来翻译上述语句?
最佳答案
您为特定生命周期注册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() );
关于c# - UserStore 每个 HttpRequest 的 Unity IoC 生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22894369/