-
Notifications
You must be signed in to change notification settings - Fork 11
Description
Hello,
In our project, we use implementations of IAuthorizationHandler
which use the scoped lifecycle. Unfortunately this is not compatible with graphql-aspnet
because SchemaItemAuthorizationMiddleware
is registered as a singleton.
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: GraphQL.AspNet.Middleware.SchemaItemSecurity.Components.SchemaItemAuthorizationMiddleware Lifetime: Singleton ImplementationType: GraphQL.AspNet.Middleware.SchemaItemSecurity.Components.SchemaItemAuthorizationMiddleware': Cannot consume scoped service 'Microsoft.AspNetCore.Authorization.IAuthorizationHandler' from singleton 'GraphQL.AspNet.Middleware.SchemaItemSecurity.Components.SchemaItemAuthorizationMiddleware'.)
Please can you make the lifecycles configurable?
A dirty dirty hack in case anybody needs it:
public static IServiceCollection ChangeServiceLifecycle<TService>(this IServiceCollection services, ServiceLifetime newLifetime)
{
var existingServiceDescriptor = services.Single(serviceDescriptor => serviceDescriptor.ServiceType == typeof(TService));
if (existingServiceDescriptor.Lifetime == newLifetime)
{
return services;
}
if (existingServiceDescriptor.ImplementationInstance is not null)
{
throw new InvalidOperationException("Cannot change the lifecycle of a dependency with a specific implementation instance");
}
services.Remove(existingServiceDescriptor);
if (existingServiceDescriptor.ImplementationFactory is not null)
{
services.Add(new ServiceDescriptor(existingServiceDescriptor.ServiceType, existingServiceDescriptor.ImplementationFactory, newLifetime));
}
else if (existingServiceDescriptor.ImplementationType is not null)
{
services.Add(new ServiceDescriptor(existingServiceDescriptor.ServiceType, existingServiceDescriptor.ImplementationType, newLifetime));
}
else
{
throw new InvalidOperationException("Unexpected service descriptor configuration");
}
return services;
}
builder.Services.ChangeServiceLifecycle<SchemaItemAuthorizationMiddleware>(ServiceLifetime.Scoped);