I am trying to get a dependency injected into the constructor of a custom authorization handler, but the AddAuthorization
in asp.net is making it difficult.
Handler:
class MyHandler : AuthorizationHandler<MyRequirement>
{
readonly IDependent dependency;
public UserExistsHandler(IDependent dependency)
{
this.dependency = dependency;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
context.Succeed(requirement);
}
}
Program.cs
builder.Services.AddSingleton<IAuthorizationHandler, MyHandler>();
builder.Services.AddAuthorization(config =>
{
config.AddPolicy("MyPolicy", policy =>
{
// how?
policy.AddRequirements(new )
});
});
According to official documentation this should be possible: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/dependencyinjection?view=aspnetcore-6.0
However, the signature for AddRequirements
is not generic and requires me to pass an actual instance of the handler which I cannot do because I have no reference to the IServiceProvider
in the config delegate.
How do I register the handler without having to create a new instance to be registered which defeats the purpose of the DI I am trying to do?
CodePudding user response:
It's not the handler that you need to pass to AddRequirements
, but the an instance of MyRequirement
.
builder.Services.AddAuthorization(config =>
{
config.AddPolicy("MyPolicy", policy =>
{
policy.AddRequirements(new MyRequirement());
});
});