gpt4 book ai didi

c# - UserStore 的每个 HttpRequest 的 Unity IoC 生命周期

转载 作者:行者123 更新时间:2023-11-30 20:49:59 25 4
gpt4 key购买 nike

我正在尝试清理新 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com