Home > front end >  How to create Type variable of interface, having generic types of mentioned interface using reflecti
How to create Type variable of interface, having generic types of mentioned interface using reflecti

Time:10-06

I have a generic interface:

    public interface ICacheRequestHandler<in TRequest, TResponse>
    {
        Task<TResponse> HandleAsync(TRequest request, CancellationToken cancellationToken = default);
    }

I would like to get Type variable of interface with given TRequest and TResponse to make it possible to request correct service implementing the mentioned interface in the DI. Something like this:

        public async Task<TResponse> Handle(
            TRequest request,
            CancellationToken cancellationToken,
            RequestHandlerDelegate<TResponse> next)
        {
            using var scope = serviceProvider.CreateScope();
            var requestType = request.GetType();
            var responseType = typeof(TResponse);
            scope.ServiceProvider.GetService(typeof(ICacheRequestHandler<requestType, responseType>)) // How to get this working? :) 

        }

Thank you so much for any help in advance. Regards

CodePudding user response:

Use Type.MakeGenericType like this:

var serviceType = typeof(ICacheRequestHandler<,>)
    .MakeGenericType(requestType, responseType);

scope.ServiceProvider.GetService(serviceType);

This uses the open-generic Type of ICacheRequestHandler and applies the generic arguments at runtime.

  • Related