Moving Identity 2.0 functions to repository class

2019-02-25 09:59发布

I am using identity 2.0 for my application and want to move the data functionalities to repository layer such as the following code:

    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>();

now the problem is HttpContext doesn't live in the repository layer and you have to pass it to that layer. but even if you do that, the call should be coming from the Web layer. yet you don't want to include userManager in every call to other layers. any solution?

1条回答
我想做一个坏孩纸
2楼-- · 2019-02-25 10:26

i found the way to create the user manager on the repository layer:

            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");
查看更多
登录 后发表回答