如何从startup.cs向我的类注入RoleManager? 这是我的代码: 在这里,我想收到RoleManager CustomRoleRequirement.cs
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
private readonly RoleManager<Role> _roleManager;
public CustomRoleRequirement(RoleManager<Role> roleManager)
{
_roleManager = roleManager;
}
}
从这里注入Startup.cs
services.AddAuthorization(options =>
{
options.AddPolicy("AccountManager", policy => policy.AddRequirements(new CustomRoleRequirement()));
});
答案 0 :(得分:1)
将services.AddIdentity<...>
添加到Startup
课程。如果您使用带有Identity的模板创建项目,它将会存在。身份已经注入RoleManager<TRole>
。
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();