首页 > 解决方案 > 在中间件、控制器和后台服务之间共享单例

问题描述

我打算将一些数据放入中间件的集合中。我想通过控制器查看这些数据。我想通过后台服务减少这个集合中的数据量。

ConfigureServices()中,我映射了一个我想与控制器、后台服务和中间件共享的单例。例如:

ConcurrentQueue<string> sharedData = new ConcurrentQueue<string>();
services.AddSingleton(typeof(ConcurrentQueue<string>), sharedData);

这个单例被注入我的控制器和后台服务就好了。有谁知道我如何从我的中间件访问这个单例?

标签: c#asp.net-core

解决方案


您的中间件上下文具有IServiceProvider属性RequestServices.

例如

var queue = context.RequestServices.GetService<ConcurrentQueue<string>>();

此外,正如 Tseng 所指出的,当使用基于工厂的方法实现IMiddleware接口时,中间件可以具有构造函数依赖注入。

例如

public class ConcurrentQueueMiddleware : IMiddleware
{
    private readonly ConcurrentQueue<string> _queue;

    public ConcurrentQueueMiddleware(ConcurrenQueue<string> queue)
    {
        _queue = queue;
    }

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        // do stuff with your queue

        await next(context);
    }
}

更多信息可以在微软官方文档https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/extensibility?view=aspnetcore-2.0中找到


推荐阅读