将UserManager和UserStore从AccountController移出?

3

这样就可以了吗?还是我也需要处理 UserStore?如果需要的话,欢迎提出建议。我对ASP.NET Identity还不熟悉。

using (var applicationDbContext = new ApplicationDbContext())
{
    using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(applicationDbContext)))
    {

    }
}

我想这样可能更好:

我猜应该是这样:

using (var applicationDbContext = new ApplicationDbContext())
{
    using (var userStore = new UserStore<ApplicationUser>(applicationDbContext))
    {
        using (var userManager = new UserManager<ApplicationUser>(userStore))
        {

        }
    }
}

编辑:很高兴我提出了这个问题,尽管我可能已经回答了我的最初的问题。感谢Glenn Ferrie,我会查看ASP.NET依赖注入。


2
你应该使用ASP.NET依赖注入,不要自己维护这些实例的生命周期。你正在使用OWIN吗? - Glenn Ferrie
我正在使用OWIN。将查看ASP.NET依赖注入。感谢您指引我正确的方向。无论如何...我的答案中的代码是否足够“好”/“安全”? - Jo Smo
1
如果您正在使用VS 2013或VS 2015 RC,并且创建了一个ASP.NET Web应用程序,您可以在此处找到代码:.\App_Start\Startup.Auth.cs--祝您好运。 - Glenn Ferrie
@GlennFerrie 再次感谢! - Jo Smo
1个回答

2
这是一些代码片段,来自使用VS 2015 RC创建的新ASP.NET MVC (.NET 4.6)。首先是Startup类:
public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
// rest of implementation ommitted for brevity.

如果您想在控制器类中访问它,则可以按照以下方式进行操作:
public class AccountController : Controller
{
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    // NOTE: ASP.NET will use this contructor and inject the instances
    // of SignInManager and UserManager from the OWIN container
    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }
    // there are implementations for the public properties
    // 'UserManager' and 'SignInManager' in the boiler plate code
    //  not shown here

愉快编码!


1
如果我不在控制器内部,这个会起作用吗?哪些地方上下文中没有context.Get()或者无法访问它? - Jo Smo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接