c# - 在中间件、控制器和后台服务之间共享单例
问题描述
我打算将一些数据放入中间件的集合中。我想通过控制器查看这些数据。我想通过后台服务减少这个集合中的数据量。
在ConfigureServices()
中,我映射了一个我想与控制器、后台服务和中间件共享的单例。例如:
ConcurrentQueue<string> sharedData = new ConcurrentQueue<string>();
services.AddSingleton(typeof(ConcurrentQueue<string>), sharedData);
这个单例被注入我的控制器和后台服务就好了。有谁知道我如何从我的中间件访问这个单例?
解决方案
您的中间件上下文具有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中找到
推荐阅读
- r - R闪亮从相同的输出函数中检索表并在ui中并排显示
- laravel-5.2 - 将对象数组转换为整数数组
- javascript - 在 wicked_pdf 中编号非 1 的页面
- sql - dbGetQuery 检索的行数较少
- java - Java Websocket 在向同一个套接字发出下一个请求之前等待响应
- ruby-on-rails-5 - 在rails api中显示不带括号的错误消息
- node.js - 如何使用 node.js 从两个不同的数据库系统中检索数据?
- ssl-certificate - 如何将签名证书添加到现有的 Google Cloud vm
- git - git - 与分支头混淆?
- angular - Mat-datepicker 通过 API 服务将当前日期发送到我的数据库