Moving Identity 2.0 functions to repository class

痴心易碎 提交于 2019-12-01 22:56:01

问题


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:


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


来源:https://stackoverflow.com/questions/23861196/moving-identity-2-0-functions-to-repository-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!