我有一个要测试的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开始规范托管服务?
答案 0 :(得分:8)
托管服务由框架启动,是WebHost启动过程的一部分
// Fire IHostedService.Start
await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);
通过HostedServiceExecutor
,它将收集所有已注册的IHostedService
,将它们枚举并依次启动
public HostedServiceExecutor(ILogger<HostedServiceExecutor> logger, IEnumerable<IHostedService> services)
{
_logger = logger;
_services = services;
}
public async Task StartAsync(CancellationToken token)
{
try
{
await ExecuteAsync(service => service.StartAsync(token));
}
catch (Exception ex)
{
_logger.ApplicationError(LoggerEventIds.HostedServiceStartException, "An error occurred starting the application", ex);
}
}
但是,由于您要单独测试托管服务,因此您必须充当框架并自己启动服务。
[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 service = serviceProvider.GetService<IHostedService>() as QueuedHostedService;
var backgroundQueue = serviceProvider.GetService<IBackgroundTaskQueue>();
await service.StartAsync(CancellationToken.None);
var isExecuted = false;
backgroundQueue.QueueBackgroundWorkItem(async (sp, ct) => {
isExecuted = true;
});
await Task.Delay(10000);
Assert.IsTrue(isExecuted);
await service.StopAsync(CancellationToken.None);
}