将Identity 2.0功能移动到存储库类

时间:2014-05-26 00:20:42

标签: 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) {
        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。任何解决方案?

1 个答案:

答案 0 :(得分: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");