【发布时间】:2014-04-10 02:30:39
【问题描述】:
我正在尝试清理新的 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 生命周期管理翻译上述语句?
【问题讨论】:
标签: c# dependency-injection unity-container asp.net-mvc-5 asp.net-identity