c# - 如何将 DbContextPool 与 Singleton 一起使用?
问题描述
在我的应用程序中,我正在使用 NMS 和 ActiveMQ 进行集成。我有一些监听器是单例监听一些消息队列。收到消息后,侦听器应对其进行处理并将其记录在数据库中。MyDbContext
是使用以下DbContextPool
选项配置的:
services.AddEntityFrameworkSqlServer();
services.AddDbContextPool<MyContext>((serviceProvider, options) =>
{
options.UseSqlServer(connectionString);
options.UseInternalServiceProvider(serviceProvider);
});
因此,当我尝试将其DbContext
注入我的ActiveMqListener
班级时,我得到了错误:
InvalidOperationException: Cannot consume scoped service 'MyApp.Data.MyContext' from singleton 'MyApp.Integrations.ActiveMqListener'.
一旦我的工作完成处理一条消息,如何获取池中的一个上下文并释放它?还有其他推荐的方法吗?
提前致谢。
解决方案
从单例解析作用域服务是很危险的。可能会导致服务在处理后续请求时状态不正确。
默认情况下AddDbContext
或AddDbContextPool
注册DbContext
为Scoped
服务。您正在使用已注册为服务DbContext
的课堂。那就是问题所在!ActiveMqListener
Singleton
解决方案是:在方法中注册您ActiveMqListener
的 ASP.NET Core DI 。ScopedService
Startup.ConfigureServices
注意:如果您有义务使用ActiveMqListener
as,请按以下方式Singleton
注册您的DbConext
as Singleton
:
services.AddDbContext<MyContext>((serviceProvider, options) =>
{
options.UseSqlServer(connectionString);
options.UseInternalServiceProvider(serviceProvider);
}, ServiceLifetime.Singleton); // <-- Here it is
推荐阅读
- r - 在 R 中为多个观察创建向量
- android - 有没有办法在我的 android 应用程序中利用我的手机(以前,主页)中的按钮导航栏,这样我就不必创建一个定制的导航栏
- powershell - 如何找到 Outlook 的路径,以便我可以发送带有脚本的电子邮件
- python - Python - Sonarcube 与 pylint 之间的区别
- excel - 我的文本框 VBA 代码不包括单元格值中的最终输入
- python - For 循环打印在终端而不是在 Excel 文件中
- python - Just started learning python in college for a password generator
- python - Odoo 11 模块升级 - KeyError: 'sequence'
- r - 如何从字符串中提取数字?
- javascript - 谁能解释这段代码: