如何从Startup中将RoleManager <role>注入我的类?

时间:2017-11-01 22:03:34

标签: c# asp.net-core asp.net-core-identity

如何从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()));
            });

1 个答案:

答案 0 :(得分:1)

services.AddIdentity<...>添加到Startup课程。如果您使用带有Identity的模板创建项目,它将会存在。身份已经注入RoleManager<TRole>

services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();