我一直试图从asp.net核心身份中获取所有角色的列表,这是我在使用控制器之前所做的工作:
public AdminController(
UserManager<ApplicationUser> userManager,
ILogger<AccountController> logger,
IEmailSender emailSender,
RoleManager<IdentityRole> roleManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_logger = logger;
_emailSender = emailSender;
_roleManager = roleManager;
_signInManager = signInManager;
}
private void PuplateRolesList(RegisterViewModel model)
{
model.Roles = _roleManager.Roles?.ToList();
}
我想做的是有一个可以重用的类,该类将传回所有角色的列表,而不使用控制器,我尝试这样做:
var roleStore = new RoleStore<AppRole, int, AppUserRole>(dbContext);
var roleMngr = new RoleManager<AppRole, int>(roleStore);
但是在一个类中,它显然没有构造角色管理器或dbContect,所以我自己尝试了一下,但它不起作用。关于如何在应用程序中添加类的任何想法都可以提供列表或角色,以至于我的控制器中没有全部内容?
谢谢
答案 0 :(得分:3)
创建一个类:
public class RoleUtility
{
private readonly RoleManager<IdentityRole> _roleManager;
public RoleUtility(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
public void PopulateRolesList(RegisterViewModel model)
{
model.Roles = _roleManager.Roles?.ToList();
}
}
提取界面:
public interface IRoleUtility
{
void PopulateRolesList(RegisterViewModel model);
}
RoleUtility
类声明变为:
public class RoleUtility: IRoleUtility
然后,在您的Startup
类中:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddTransient<IRoleUtility, RoleUtility>();
}
您的控制器代码变为:
public AdminController(
UserManager<ApplicationUser> userManager,
ILogger<AccountController> logger,
IEmailSender emailSender,
IRoleUtility roleUtility,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_logger = logger;
_emailSender = emailSender;
_roleUtility = roleUtility;
_signInManager = signInManager;
}
private void PuplateRolesList(RegisterViewModel model)
{
_roleUtility.PopulateRolesList(model);
}