gpt4 book ai didi

c# - 控制台应用程序后台服务中 httpclientfactory 的 DI

转载 作者:行者123 更新时间:2023-12-02 16:52:18 26 4
gpt4 key购买 nike

我有一个带有简单消费后台服务的控制台程序,它需要从使用 HttpClientFactory 的作用域服务调用函数来调用外部 API 并将结果返回给消费后台服务。

在查看了几个在线示例后,我想要非常简单,以消除代码中所有可能的复杂性。

public class Program
{
public static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureLogging((hostContext, config) =>
{
config.AddConsole();
})
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddJsonFile("appsettings.json", optional: true);
config.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true);
config.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ConsumeMessageService>();
services.AddScoped<IScopedArcGisServices, ScopedArcGisServices>();
})
.UseConsoleLifetime()
.Build();

using (host)
{
// Start the host
await host.StartAsync();

// Wait for the host to shutdown
await host.WaitForShutdownAsync();
}
}
}
public class ConsumeMessageService : IHostedService
{
private readonly ILogger _logger;
public IServiceProvider _serviceProvider { get; }

public ConsumeMessageService(IServiceProvider services,
ILogger<ConsumeMessageService> logger)
{
_serviceProvider = services;
_logger = logger;
}

public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation(
"Consume message service hosted service is starting.");

DoWork();

return Task.CompletedTask;
}

private void DoWork()
{
_logger.LogInformation(
"Consume message service hosted service is working.");

using (var scope = _serviceProvider.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedServices>();

scopedProcessingService.DoWork();
}
}

public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is stopping.");

return Task.CompletedTask;
}
}
internal interface IScopedServices
{
void DoWork();
}

internal class ScopedServices : IScopedServices
{
private readonly ILogger _logger;
private readonly IHttpClientFactory _clientFactory;
public string JsonResult { get; private set; }

public ScopedServices(ILogger<ScopedServices> logger, IHttpClientFactory clientFactory)
{
_logger = logger;
_clientFactory = clientFactory;
}

public void DoWork()
{
_logger.LogInformation("Scoped processing service is working.");
}
}

一旦我有了 HttpClientFactory 的 scopedservice,我就会收到这条消息:

Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'Integration.BackgroundService.Services.ScopedServices'.'

最佳答案

IHttpClientFactory 默认不添加。

配置服务时必须调用services.AddHttpClient()来添加对工厂及其相关客户端的访问。

//...
.ConfigureServices((hostContext, services) => {
services.AddHttpClient(); //<-- THIS IS NEEDED
services.AddHostedService<ConsumeMessageService>();
services.AddScoped<IScopedArcGisServices, ScopedArcGisServices>();
})
//...

有关如何配置工厂创建的客户端的更多信息,

引用Use HttpClientFactory to implement resilient HTTP requests

关于c# - 控制台应用程序后台服务中 httpclientfactory 的 DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57992886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com