我有一个我想测试的 QueueTask 托管服务(.NET Core 的新后台服务)。我的 queuedHosted 服务如下所示:
public QueuedHostedService(IServiceProvider serviceProvider, IBackgroundTaskQueue taskQueue, ILoggerFactory loggerFactory)
{
TaskQueue = taskQueue;
_logger = loggerFactory.CreateLogger<QueuedHostedService>();
_serviceProvider = serviceProvider;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _serviceProvider.CreateScope())
{
while (false == stoppingToken.IsCancellationRequested)
{
var workItem = await TaskQueue.DequeueAsync(stoppingToken);
try
{
await workItem(scope.ServiceProvider, stoppingToken);
}
catch (Exception ex)
{
this._logger.LogError(ex, $"Error occurred executing {nameof(workItem)}.");
}
}
}
}
它只是从队列中读取任务并在它们进入时执行它们。我已经验证了托管服务正在生产中工作。我为它写了一个测试,如下所示:
[TestMethod]
public async Task Verify_Hosted_Service_Executes_Task()
{
IServiceCollection services = new ServiceCollection();
services.AddSingleton<ILoggerFactory, NullLoggerFactory>();
services.AddHostedService<QueuedHostedService>();
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
var serviceProvider = services.BuildServiceProvider();
var backgroundQueue = serviceProvider.GetService<IBackgroundTaskQueue>();
var isExecuted = false;
backgroundQueue.QueueBackgroundWorkItem(async (sp, ct) => {
isExecuted = true;
});
await Task.Delay(10000);
Assert.IsTrue(isExecuted);
}
但是,我的回调从未被击中。如何让我的任务在后台服务上执行?
编辑
我在模仿启动,并假设我的后台服务可以正常工作,但显然我的服务从未启动。
托管服务通常如何从 .NET Core 启动?