Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Identity 2.0 functions to repository class

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 [email protected] 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?

like image 325
user3311522 Avatar asked Nov 23 '25 10:11

user3311522


1 Answers

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");
like image 123
user3311522 Avatar answered Nov 25 '25 00:11

user3311522



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!