在AccountController之外处理UserManager和UserStore



这足够好吗?还是我也必须处理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依赖项注入。

这是使用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

快乐编码!

相关内容

  • 没有找到相关文章

最新更新