好吧,经过大量的挖掘和幸运的发现 - 事实证明 Microsoft.AspNet.Identity.Core 带有一些其他接口,特别是,IUserRoleStore<TUser>
它们IUserPasswordStore<TUser>
都“继承”(实现) IUserStore<TUser>。
因此,如果我们想要角色管理功能,我们实现IUserRoleStore<TUser>
:
class MyUser : IUser
{
// Additional properties and functions not shown for brevity.
}
class MyUserStore : IUserRoleStore<MyUser>
{
public bool IsInRole(string username, string role)
{
// Implementation not show for brevity.
}
/* We would then implement the rest of the required functions.
We would have a data context here that has access to users,
user-roles, and roles.
*/
}
现在我们可以传递MyUserStore
给UserManager<TUser>
, 因为MyUserStore
是一个IUserRoleStore<TUser>
, 这是一个IUserStore<TUser>
:
UserManager<MyUser> UM = new UserManager<MyUser>(new MyUserStore());
然后,我怀疑源代码UserManager<TUser>
使用反射来确定在构造函数中传递给它的存储是否实现了IUserStore<TUserStore>
“子接口”之一,以便能够执行角色检查(如果它实现IUserRoleStore<TUser>
)或密码集/reset(如果它实现了IUserPasswordStore<TUser>
)。
我希望你觉得这很有用,因为大多数文档(MVC 教程等)都没有告诉我们这个细节。他们告诉我们使用UserStore<TUser>
Microsoft.AspNet.Identity.EntityFramework 的实现——我们所要做的就是传入一个自定义User
对象(实现IUser
),我们就可以开始了。