Your approach where the UserManager
is registered for specific lifetime is correct. However, I don't understand why it even compiles, since your HttpContextLifetimeManager
expects the HttpContext
as a parameter.
Another issue is that your implementation is wrong. The parameterless constructor takes current http context, however you rather want the lifetime manager to use the context the instance is created on rather the one the type is registered on. If the parameterless constructor is used, this could lead to http context mismatch issues.
First, change your implementation to
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;
}
}
and then register your type
container.RegisterType<UserManager<ApplicationUser>>( new HttpContextLifetimeManager() );