System.InvalidoperationException:'在上下文实例完成之前,在此上下文实例上开始了第二次操作。这通常是由使用dbContext同一实例同时引起的。有关如何避免DBContext线程问题的更多信息,请参见
Https://go.microsoft.com/fwlink/?linkId =2097913.'
。我正在使用依赖注入来实例化
DbContext
并将其注入服务构造仪。 这就是我在program.cs文件中添加服务的方式:
var serviceCollection = new ServiceCollection();
var serviceProvider = serviceCollection
.AddSingleton<IGymService, GymService>()
.AddSingleton<ISettingsService, SettingsService>()
.AddSingleton<ICommService, CommService>()
.AddSingleton<IProtocolService, ProtocolService>()
.AddDbContext<MyLocalContext>(options =>
{
options.UseSqlServer(settings.DbConnection, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
})
.BuildServiceProvider();
首先,我认为这是因为所有服务都是单人的,但是,我也尝试了AddScoped和Addransient,但也会发生同样的情况。
我如何摆脱这个问题?也许每次使用它时打开连接,但我不知道该怎么做。 我也想使用
using (var db = new MyLocalContext(...)) { }
,但我不知道这是否是一个很好的解决方案。链接错误消息指向的链接没有提供任何解决方案。它只解释了问题。
任何提示?二,您不想分享您
DbContext
IDbContextFactory
var serviceCollection = new ServiceCollection();
var serviceProvider = serviceCollection
.AddSingleton<IGymService, GymService>()
.AddSingleton<ISettingsService, SettingsService>()
.AddSingleton<ICommService, CommService>()
.AddSingleton<IProtocolService, ProtocolService>()
.AddDbContext<MyLocalContext>(options =>
{
options.UseSqlServer(settings.DbConnection, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
})
.AddDbContextFactory<OtcDbContext>() // Add lifetime here if necessary
.BuildServiceProvider();
usage:
using (var dbContext = await _otcDbContextFactory.CreateDbContextAsync())
{
// Do Stuff here
}