【发布时间】:2015-08-26 23:23:51
【问题描述】:
我的 MVC 应用程序中有一个 Singleton 模型类,用于确定登录用户是否具有授权/管理员权限(基于某些 AD 组的成员资格)。这个模型类需要是一个 Singleton 以便用户的访问权限可以在第一次登录时建立一次并在整个会话中使用:
public sealed class ApplicationUser
{
// SINGLETON IMPLEMENTATION
// from http://csharpindepth.com/articles/general/singleton.aspx#lazy
public static ApplicationUser CurrentUser { get { return lazy.Value; } }
private static readonly Lazy<ApplicationUser> lazy =
new Lazy<ApplicationUser>(() => new ApplicationUser());
private ApplicationUser()
{
GetUserDetails(); // determine if user is authorized/admin
}
// Public members
public string Name { get { return name; } }
public bool IsAuthorized { get { return isAuthorized; } }
public bool IsAdmin { get { return isAdmin; } }
// Private members
// more code
}
Singleton 第一次在我的所有其他控制器派生自的 EntryPointController 中实例化:
public abstract class EntryPointController : Controller
{
// this is where the ApplicationUser class in instantiated for the first time
protected ApplicationUser currentUser = ApplicationUser.CurrentUser;
// more code
// all other controllers derive from this
}
这种模式允许我在整个应用程序中使用ApplicationUser.CurrentUser.Name 或ApplicationUser.CurrentUser.IsAuthorized 等。
但是,问题是这样的:
Singleton 包含在 Web 应用程序启动时登录的第一个用户的引用!所有后续登录的用户都会看到最早登录用户的名称!
如何使单例会话具体化?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-5 singleton