2015-07-03 28 views
3

這夠好嗎?或者我還必須處置UserStore以及?如果我確實需要任何建議,歡迎。我是ASP.NET Identity的新手。在AccountController之外放置UserManager和UserStore?

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依賴注入。

+1

您應該使用ASP.NET依賴注入,並且不要自己維護這些實例的生命週期。你在使用OWIN嗎? –

+0

我正在使用OWIN。將檢查ASP.NET依賴注入。謝謝你指出我朝着正確的方向。無論如何......我的答案中的代碼是否足夠「好」/「安全」? –

+1

如果您使用的是VS 2013或VS 2015 RC,並且您選擇了「文件>新建項目」並創建ASP.NET Web應用程序,那麼您會在此處找到代碼:'。\ App_Start \ Startup.Auth.cs' - 很好運氣 –

回答

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 

編碼快樂!

+0

如果我不在控制器內部,這項工作是否可行? context.Get()不存在/不可訪問的地方? –

相關問題