mercredi 6 octobre 2021

How to create Type variable of interface, having generic types of mentioned interface using reflection in C#?

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





Aucun commentaire:

Enregistrer un commentaire