其他分享
首页 > 其他分享> > 与IMediatR库一起使用时,无法在类型化的客户端中注入HttpClient

与IMediatR库一起使用时,无法在类型化的客户端中注入HttpClient

作者:互联网

根据ASP.NET Core 2.2文档在MSDN中提供的示例,可以通过在Startup.cs中添加以下行来将HttpClient注入类型化的客户端(服务类):

// Startup.cs
services.AddHttpClient<GitHubService>();

从控制器类来看,它看起来像(从现在开始,我将使用GitHub作为域模型的简化):

// GitHubController.cs
public class GitHubController : Controller
{
    private readonly GitHubService _service;
    public GitHubController(GitHubService service)
    {
        _service = service;
    }
}

但是,我在项目中使用MediatR库,因此我的项目结构看起来有些不同.我有2个项目-GitHubFun.Api,GitHubFun.Core-分别是ASP.NET Core 2.2 API项目和.NET Core 2.2类库.

我的控制器:

// GitHubController.cs
public class GitHubController : Controller
{
    private readonly IMediator _mediator;
    public GitHubController(IMediator mediator)
    {
        _mediator= mediator;
    }

    public async Task<IActionResult> GetGitHubRepositoryInfo(
        GetGitHubRepositoryCommand command)
    {
         _mediator.Send(command);
    }
}

和我的处理程序类:

// GetGitHubRepositoryHandler.cs
public class GetGitHubRepositoryHandler : 
    IRequestHandler<GetGitHubRepositoryCommand , GetGitHubRepositoryCommandResult>
{
    private HttpClient _httpClient;

    public GetGitHubRepositoryHandler(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
}

当我发出HTTP请求并调用API方法时,它成功注入了IMediator,但在_mediator.Send(command)行上引发了异常.

异常主体:

System.InvalidOperationException: Error constructing handler for request of type MediatR.IRequestHandler`2[IDocs.CryptoServer.Core.Commands.ExtractX509Command,IDocs.CryptoServer.Core.Commands.ExtractX509CommandResult]. Register your handlers with the container. See the samples in GitHub for examples. —> System.InvalidOperationException: Unable to resolve service for type ‘System.Net.Http.HttpClient’ while attempting to activate ‘IDocs.CryptoServer.Core.Handlers.ExtractX509CommandHandler’

(ExtractX509CommandHandler-只是一个真实的域模型,而不是GetGitHubRepositoryHandler).

似乎ASP.NET Core DI无法解析DI并将HttpClient注入处理程序.

我的Startup.cs包含以下几行:

services.AddHttpClient<ExtractX509CommandHandler>();
services.AddMediatR(
       typeof(Startup).Assembly, 
       typeof(ExtractX509CommandHandler).Assembly);

解决方法:

我找到了解决方案.由于某些原因,在这种情况下,我们需要将Microsoft.Extensions.Http.dll的IHttpClientFactory而不是HttpClient传递给处理程序类.我只更改了一行,它是:

public GetGitHubRepositoryHandler(HttpClient httpClient)

现在:

public GetGitHubRepositoryHandler(IHttpClientFactory httpClientFactory)

现在它可以正常工作了.我不知道它为什么起作用,所以如果有人可以解释将IHttpClientFactory和HttpClient注入类之间的区别,那将是完美的.

标签:asp-net-core-2-0,mediatr,c
来源: https://codeday.me/bug/20191211/2105633.html