如何创建接口的类型变量,在 C# 中使用反射具有上述接口的通用类型?

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

我有一个通用接口:

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

我想使用给定的 TRequest 和 TResponse 获取接口的 Type 变量,以便请求正确的服务实现 DI 中提到的接口。像这样:

        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? :) 

        }

非常感谢您提前提供的帮助。问候

像这样使用Type.MakeGenericType

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

scope.ServiceProvider.GetService(serviceType);

这使用 ICacheRequestHandler 的开放通用 Type 并在运行时应用通用参数。