簡體   English   中英

在AccountController之外放置UserManager和UserStore?

[英]Disposing UserManager and UserStore outside of AccountController?

這夠好嗎? 或者我是否也必須處置UserStore 如果我有任何建議,歡迎。 我是ASP.NET身份的新手。

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.

那么這是你在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

快樂的編碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM