C# 将Identity 2.0功能移动到存储库类
我正在为我的应用程序使用identity 2.0,并希望将数据功能移动到存储库层,如以下代码:C# 将Identity 2.0功能移动到存储库类,c#,entity-framework,asp.net-mvc-5,asp.net-identity-2,C#,Entity Framework,Asp.net Mvc 5,Asp.net Identity 2,我正在为我的应用程序使用identity 2.0,并希望将数据功能移动到存储库层,如以下代码: public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { InitializeIdentityForE
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> {
protected override void Seed(ApplicationDbContext context) {
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create User=Admin@Admin.com with password=Admin@123456 in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db) {
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
公共类应用程序BinInitializer:DropCreateDatabaseIfModelChanges{
受保护的重写无效种子(ApplicationDbContext上下文){
InitializeIdentityFore(上下文);
种子(上下文);
}
//创建用户=Admin@Admin.com带密码=Admin@123456在管理员角色中
公共静态void initializedEntityForef(ApplicationDbContext数据库){
var userManager=HttpContext.Current.GetOwinContext().GetUserManager();
var rolemager=HttpContext.Current.GetOwinContext().Get();
现在的问题是
HttpContext
不存在于存储库层,您必须将其传递到该层。但即使您这样做,调用也应该来自Web
层。但是您不希望在对其他层的每次调用中都包含userManager
。有解决方案吗?我找到了创建用户m的方法存储库层上的管理器:
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "sallen" };
userManager.Create(user, "password");
roleManager.Create(new IdentityRole { Name = "admin" });
userManager.AddToRole(user.Id, "admin");
var-roleStore=新的roleStore(上下文);
var roleManager=新roleManager(roleStore);
var userStore=新的userStore(上下文);
var userManager=newusermanager(userStore);
var user=newapplicationuser{UserName=“sallen”};
创建(用户,“密码”);
Create(新的IdentityRole{Name=“admin”});
userManager.AddToRole(user.Id,“admin”);