如何在管道中提供来自HostedService的数据

时间:2019-03-28 19:44:27

标签: asp.net-core-2.1

我使用this示例创建了定时后台任务。使用此后台任务,我有一个每x秒更新一次的值,可以正常工作。

但是,我希望能够在中间件管道中使用此值。如何实现的?我可以使用诸如全局变量之类的东西还是以某种方式引用HostedService吗?

定时后台服务

开始使用ConfigureServices services.AddHostedService << >>();

{
public class TimerService : IHostedService, IDisposable
    {
        private readonly ILogger _logger;
        private Timer _timer;

        public TimerService (ILogger<TimerService> logger)
        {
            _logger = logger;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is starting.");

            _timer = new Timer(DoWork, null, TimeSpan.Zero,
                TimeSpan.FromSeconds(1));

            return Task.CompletedTask;
        }

        private async void DoWork(object state)
            {
            //Do your stuff here
            await Task.Delay(50);
            _logger.LogInformation("Timed Background Service is executing.");
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Timed Background Service is stopping.");

            _timer?.Change(Timeout.Infinite, 0);

            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}

中间件管道

使用配置启动

    public async Task Invoke(HttpContext context, ILogger<APIKeyHandler> logger, IConfiguration configuration)
    {
        _logger = logger;

        bool KeyInHeader = context.Request.Headers.ContainsKey("Key");

        if (KeyInHeader)
        {
            if (context.Request.Headers["Key"] = *!!VALUE COLLECTED USING THE TimerService*!!)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                await context.Response.WriteAsync($"Executed");
            }
        }
    }

当前无法从TimerService获取值。我希望能够引用Timerservice.LatestValue之类的东西。如果这不是通往我的道路,那么我很想获得一些指导。

0 个答案:

没有答案