将自定义类注入AuthorizationHandler

时间:2017-01-17 11:27:30

标签: c# asp.net-core

我有自定义政策来检查某些授权。

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IPermissionsManager, PermissionsManager>();

    services.AddAuthorization(options =>
    {
        options.AddPolicy("HasPermission",
            policy => policy.Requirements.Add(new CheckProjectAccessLevelRequirement()));
    });

    services.AddSingleton<IAuthorizationHandler, CheckProjectAccessLevelHandler>();
}

在CheckProjectAccessLevelHandler中我想使用PermissionsManager。

public class CheckProjectAccessLevelHandler : AuthorizationHandler<CheckProjectAccessLevelRequirement>
{
    readonly AuthHandlersContext _dbAuthContext;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly PermissionsManager _permissionsManager;

    public CheckProjectAccessLevelHandler(AuthHandlersContext context, UserManager<ApplicationUser> userManager, PermissionsManager permissionsManager)
    {
        _dbAuthContext = context;
        _userManager = userManager;
        _permissionsManager = permissionsManager;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CheckProjectAccessLevelRequirement requirement)
    {
        _permissionsManager.doStuff()
    }
}

但我得到了这个例外:

System.InvalidOperationException: Unable to resolve service for type 'myProject.Services.PermissionsManager' while attempting to activate 'myProject.Services.AuthHandlers.CheckProjectAccessLevelHandler'.

如果没有注入PermissionsManager,一切都按预期工作。

我想念什么?

1 个答案:

答案 0 :(得分:2)

您已将SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); IPermissionManager)注册为可解析,因此您应将ctor参数更改为services.AddTransient<IPermissionsManager, PermissionsManager>();

IPermissionsManager