我有一個通用介面:
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? :)
}
非常感謝您提前提供任何幫助。問候
uj5u.com熱心網友回復:
Type.MakeGenericType像這樣使用:
var serviceType = typeof(ICacheRequestHandler<,>)
.MakeGenericType(requestType, responseType);
scope.ServiceProvider.GetService(serviceType);
本品采用開放式通用Type的ICacheRequestHandler,并在運行時適用的一般引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311162.html
