ASP.NET Identity - 如何解耦 RoleManager(Web 层)?

ASP.NET Identity - How can I uncouple RoleManager (Web Layer)?

IoC(简单注入器)

container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>(new ApplicationDbContext()));
container.RegisterPerWebRequest<IRoleStore<IdentityRole, string>>(() => new RoleStore<IdentityRole>());

我的 ApplicationOAuthProvider 中有:

(解耦)

var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

(我对 EF 的依赖)

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

如何解耦我的 roleManager?

如本帖所述(我不确定这是否是您要找的)

如果您正在开发像 DDD 这样的 n 层架构,可以使用一种解决方法。

您将需要 2 个 class,一个用于 User,另一个用于 ApplicationUserApplicationUser 必须具有 User 的所有属性。像这样:

//DomainLayer
public class User
{
     public string Id { get; set; } 
     public string Title { get; set; }
}

//Infrastructure Layer
public class ApplicationUser
{
     public string Title { get; set; }
}

现在,诀窍是将 User class 映射到 ApplicationUser class 的相同 table。像这样:

public class UserConfig : EntityTypeConfiguration<User>
{
    public UserConfig()
    {
        HasKey(u => u.Id);

        ToTable("AspNetUsers");
    }
}

希望对您有所帮助!

ASP.NET Identity 使用 Stores 并具有一组您可以实现的接口。基本接口是 IUserStore,但为了使用 ASP.NET Identity 的其他功能,您还必须实现其他接口,例如 IUserPasswordStoreIPhoneNumberStoreThis article describes what you have to do when you want to implement your own custom stores. Here is an example 使用带有 MySQL 的自定义商店。

这不是一件容易的事,我用 Dapper 编写了自己的商店,这是很多工作,但可以完成。

我明白了 (:

No more dependencys

国际奥委会

container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new serStore<ApplicationUser>(new ApplicationDbContext()));
container.RegisterPerWebRequest<IRoleStore<ApplicationRole, string>>(() => new RoleStore<ApplicationRole>(new ApplicationDbContext()));

我在身份层创建:

public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {

    }

    public static ApplicationRoleManager Create(
    IdentityFactoryOptions<ApplicationRoleManager> options,
    IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }

并实施

var roleManager = context.OwinContext.Get<ApplicationRoleManager>();

有效!!

谢谢大家