3

我正在为我的应用程序使用身份 2.0,并希望将数据功能移动到存储库层,例如以下代码:

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

现在问题HttpContext不在存储库层中,您必须将其传递给该层。但即使你这样做,调用也应该来自该Web层。但是您不想userManager在每次调用其他层时都包含在内。任何解决方案?

4

1 回答 1

3

我找到了在存储库层创建用户管理器的方法:

            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");
于 2014-05-26T00:40:31.270 回答