entity-framework – 为什么ASP.NET SPA模板会为所有请求实例化UserManager一次?

前端之家收集整理的这篇文章主要介绍了entity-framework – 为什么ASP.NET SPA模板会为所有请求实例化UserManager一次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用VS2013 ASP.NET SPA模板作为我的Web应用程序的起点,它使用新的ASP.NET身份框架.这来自模板:
  1. public partial class Startup
  2. {
  3. static Startup()
  4. {
  5. UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
  6. ....
  7. }

因此,由于没有DbContext被传递到上面的UserStore构造函数中,这向我指示正在创建新的DbContext.由于我还想利用数据上下文(对于请求期间的其他数据操作),我稍微更改了模板代码

  1. public partial class Startup
  2. {
  3. public static DerivedDbContext=null;
  4.  
  5. static Startup()
  6. {
  7. context = new DerivedDbContext();
  8. UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(context));
  9. ...
  10. }

现在,我可以通过以下方式从我的任何控制器使用相同的DbContext:

  1. Startup.context

但是,当多个请求同时进入时我遇到了麻烦,因为无关的操作发生在同一个DbContext中.从这里开始,我向我指出,我不应该在应用程序的整个生命周期中实例化单个DbContext,而只是为了特定请求的生命周期,所以我将实例化移动到控制器的构造函数,但是现在,我在控制器中有自己的DbContext,而UserManager仍然有自己的(并且在Startup类中创建).

为什么模板为所有用户(在Startup类中)实例化了一次UserManager?值得关注的是,通过在控制器构造函数中创建自己的DbContext,有两个DbContexts(我在控制器的构造函数中创建的那个,以及在UserManager中创建的那个,在Startup类中创建的)同时播放?在所有请求中共享一个UserManager是否可以接受,但是在一般情况下在所有请求中共享一个DbContext是不可接受的?

有两个单独的上下文似乎是愚蠢的,我注意到我有时会得到一个不同步的数据视图.我想知道是否有其他人在使用此模板时遇到此问题.

**编辑:我理解像nInject这样的IOC框架可能有助于在这种情况下管理对象生命周期,但我想首先了解如何在没有这种框架的帮助下实现这一目标.

谢谢…
-ben

解决方法

因此模式应该是每个请求一个UserManager和一个DbContext.在2.0-alpha1版本中,我们尝试通过添加一些新的身份中间件来解决这两个问题:

我们正在开发一个更新的样本包来演示这些,但与此同时

您可以使用新软件包添加以下IdentityModels.cs / Startup.Auth.cs:

  1. public class ApplicationUser : IdentityUser
  2. {
  3. public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
  4. {
  5. // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
  6. var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
  7. // Add custom user claims here
  8. return userIdentity;
  9. }
  10. }
  11.  
  12. public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
  13. {
  14. public ApplicationDbContext()
  15. : base("DefaultConnection")
  16. {
  17. }
  18.  
  19. public static ApplicationDbContext Create() {
  20. return new ApplicationDbContext();
  21. }
  22. }
  23.  
  24. public class ApplicationUserManager : UserManager<ApplicationUser> {
  25. // Configure the application user manager
  26. public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) {
  27. }
  28.  
  29. public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options) {
  30. var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(options.Context.GetDbContext()));
  31. //var manager = new ApplicationUserManager(new AzureStore<ApplicationUser>());
  32. manager.UserValidator = new UserValidator<ApplicationUser>(manager) {
  33. AllowOnlyAlphanumericUserNames = false,RequireUniqueEmail = true
  34. };
  35. manager.PasswordValidator = new MinimumLengthValidator(6);
  36. var dataProtectionProvider = options.DataProtectionProvider;
  37. if (dataProtectionProvider != null) {
  38. manager.PasswordResetTokens = new DataProtectorTokenProvider(dataProtectionProvider.Create("PasswordReset"));
  39. manager.UserConfirmationTokens = new DataProtectorTokenProvider(dataProtectionProvider.Create("ConfirmUser"));
  40. }
  41. return manager;
  42. }
  43. }
  44.  
  45. public static class OwinExtensions {
  46. public static IAppBuilder UseDbContextFactory(this IAppBuilder app,Func<DbContext> createCallback) {
  47. if (app == null) {
  48. throw new ArgumentNullException("app");
  49. }
  50. if (createCallback == null) {
  51. throw new ArgumentNullException("createCallback");
  52. }
  53.  
  54. app.Use(typeof(IdentityFactoryMiddleware<DbContext,IdentityFactoryOptions<DbContext>>),new IdentityFactoryOptions<DbContext>() {
  55. Provider = new IdentityFactoryProvider<DbContext>() {
  56. OnCreate = (options) => createCallback()
  57. }
  58. });
  59. return app;
  60. }
  61.  
  62. public static DbContext GetDbContext(this IOwinContext context) {
  63. if (context == null) {
  64. throw new ArgumentNullException("context");
  65. }
  66. return context.Get<DbContext>();
  67. }
  68. }

以下内容进入Startup.Auth.cs:

  1. public void ConfigureAuth(IAppBuilder app) {
  2. // Configure the db context and user manager to use per request
  3. app.UseDbContextFactory(ApplicationDbContext.Create);
  4. app.UseUserManagerFactory(new IdentityFactoryOptions<ApplicationUserManager>() {
  5. DataProtectionProvider = app.GetDataProtectionProvider(),Provider = new IdentityFactoryProvider<ApplicationUserManager>() {
  6. OnCreate = ApplicationUserManager.Create
  7. }
  8. });
  9.  
  10. // Enable the application to use a cookie to store information for the signed in user
  11. // and to use a cookie to temporarily store information about a user logging in with a third party login provider
  12. // Configure the sign in cookie
  13. app.UseCookieAuthentication(new CookieAuthenticationOptions {
  14. AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,LoginPath = new PathString("/Account/Login"),Provider = new CookieAuthenticationProvider {
  15. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager,ApplicationUser>(
  16. validateInterval: TimeSpan.FromSeconds(5),regenerateIdentity: (manager,user) => user.GenerateUserIdentityAsync(manager))
  17. }
  18. });
  19. app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

猜你在找的asp.Net相关文章