当我在Visual Studio 2013中创建MVC 5应用程序,并选择个人帐户作为身份验证时,脚手架会自动配置ASP Net Identity。它会与ApplicationDbContext
和ApplicationUserManager
一起创建多个类。它还使用OWIN上下文注册这些类,如下所示,每个请求使用单个实例。
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);
}
基本上它会注册每个类的static Create
方法。这个静态方法负责创建该类的实例。
Quesion
1&gt;如果我不想使用静态创建方法,下面的方法是否正确?
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
public ApplicationDbContext(string connString)
: base(connString)
{
}
}
public void ConfigureAuth(IAppBuilder app)
{
var conString = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString
app.CreatePerOwinContext(()=>new ApplicationDbContext(conString));
}
2 - ;如何在不使用静态Create方法的情况下注册ApplicationUserManager
。 (必须设置UserValidator,PasswordValidator,UserTokenProvider等)
我应该在ApplicationUserManager
的构造函数中设置Validators和UserTokenProvider吗?如下所示
public class ApplicationUserManager : UserManager<ApplicationUser, string>
{
public ApplicationUserManager(ApplicationUserStore store)
: base(store)
{
base.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
base.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
base.EmailService = new EmailService();
//?????????How do I get options.DataProtectionProvider ??????
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
base.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
}
3&gt;在上面的方法中如何向OWIN上下文注册ApplicationUserManager
以便它为每个请求创建单个实例? 'ApplicationUserManager
还需要ApplicationUserStore
和ApplicationDbContext
..如何将这些传递给ApplicationUserManager
的构造函数?