我有一个带有简单消费后台服务的控制台程序,该程序需要从使用 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,我就会收到以下消息:
尝试激活“Integration.BackgroundService.Services.ScopedServices”时无法解析“System.Net.Http.IHttpClientFactory”类型的服务。