c# - 在 AccountController 之外配置 UserManager 和 UserStore?

标签 c# asp.net-mvc asp.net-identity

这够好吗?或者我还必须处理 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 依赖项注入(inject)。

最佳答案

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

然后这是在 Controller 类中访问它的方式:

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

编码愉快!

关于c# - 在 AccountController 之外配置 UserManager 和 UserStore?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196830/

相关文章:

C#:控制台正在输出无穷大(∞)

javascript - Action 与 Javascript 链接并将值传递给 Controller

c# - 了解 MVC 5 用户声明表

c# - 使用 .NET 和 Canvas 应用程序的 facebook api 获取 CanvasUrl 为空或为空

c# - 如何在 C# 中将两个整数转换为浮点值?

C# 将参数命名为替换为参数值的字符串

c# - 将 EF 模型序列化为 Json 时的循环引用

c# - Visual Studio调试错误: Site can't be reached

c# - Asp.net 身份注销不工作

asp.net-identity - 如何向IdentityServer DI框架注册ApplicationUserManager?