Home > database >  Some services are not able to be constructed in a AuthorizationHandler
Some services are not able to be constructed in a AuthorizationHandler

Time:09-28

Consider the following

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IAuthorizationHandler, AccountHandler>();
...
services.AddSingleton<IAuthorizationHandler, IsOwnerHandler>();

Now my initialize container

private void InitializeContainer()
{
  container.Register(typeof(ICommandAsyncHandler<>), typeof(ICommandAsyncHandler<>).Assembly);
  container.Register(typeof(IQueryAsyncHandler<,>), typeof(IQueryAsyncHandler<,>).Assembly);
  container.Register(typeof(IValidationHandler<>), typeof(IValidationAsyncHandler<>).Assembly);

  container.Register<IMediator, Mediator>(Lifestyle.Scoped);
  ...
}

and the handler for IsOwner

public class IsOwnerHandler : AuthorizationHandler<IsOwnerRequirement>
{
  private readonly IMediator mediator;

  protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
     IsOwnerRequirement requirement)
  {
    ...
    context.Succeed(requirement);
    return Task.CompletedTask;
  }

  public IsOwnerHandler(IMediator mediator)
  {
    this.mediator = mediator;
  }
}

the wireup class

private void IntegrateSimpleInjector(IServiceCollection services)
{
    services.AddSimpleInjector(container, options =>
    {
        options.AddAspNetCore()
            .AddControllerActivation()
            .AddViewComponentActivation()
            .AddPageModelActivation()
            .AddTagHelperActivation();
        options.AddLogging();
    });
}

I am running into the following error when the application starts

AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Authorization.IAuthorizationHandler Lifetime: Singleton ImplementationType: LM3.NNB.Gateway.WebSite.Infrastructure.Authorisation.IsOwnerHandler': Unable to resolve service for type 'LM3.NNB.Gateway.WebSite.Infrastructure.Mediator.IMediator' while attempting to activate 'LM3.NNB.Gateway.WebSite.Infrastructure.Authorisation.IsOwnerHandler'.)

I am trying to get a instance of mediator from within the handler. I can only assume that IMediator is not being registered withn the services and therefore is causing the issue. So I suspect I have not wired this up correctly.

Just in case this is needed IsOwnerHandler is an attribute on [Authorize(Policy = nameof(Policy.IsOwner))] on a razor page

The wireup for authorization is

services.AddAuthorization(options => {
    ...
    options.AddPolicy(nameof(Policy.IsOwner),
       policy => policy.Requirements.Add(new IsOwnerRequirement()));
});

CodePudding user response:

Do this:

services.AddTransient<IAuthorizationHandler>(
    _ => container.GetInstance<IsOwnerHandler>());

container.Register<IsOwnerHandler>();
  • Related