简体   繁体   English

ASP.NET 核心 API - 在前一个操作完成之前,在 Db 上下文上启动第二个操作

[英]ASP.NET Core API - Second operation is started on Db context before a previous operation completed

I'm receiving the following exception on ASP.NET core app:我在 ASP.NET 核心应用程序上收到以下异常:

"An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside 'OnConfiguring' since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe." “在配置时尝试使用上下文。DbContext 实例不能在 'OnConfiguring' 内使用,因为此时它仍在配置中。如果在前一个上下文之前启动第二个操作,则可能会发生这种情况操作已完成。不保证任何实例成员都是线程安全的。”

I know the reason why it is generating that error.我知道它产生该错误的原因。 Multiple threads in my app are at the same time trying to initialize DBContext ie from the frontend, receiving multiple requests all accessing the same method我的应用程序中的多个线程同时尝试初始化 DBContext 即从前端,接收多个请求都访问相同的方法

public async Task<IEnumerable<T>> QueryAsync<T>(string sqlStmt, Parameter[] inputParameters = null)
    {
        if (inputParameters is null)
            return await Database.GetDbConnection().QueryAsync<T>(sqlStmt);
        paramsList = new DynamicParameters();
        paramsList.AddParamater(inputParameters);
        return await Database.GetDbConnection().QueryAsync<T>(sqlStmt, paramsList);  <--Here the exception is raised
    }

If wondering what is that 'Database' referring to, then it is a DatabaseFacade type property inside DbContext class of EFCore 6.0.9;如果想知道“数据库”指的是什么,那么它是 EFCore 6.0.9 的 DbContext class 内的 DatabaseFacade 类型属性; here's the code:这是代码:

namespace Microsoft.EntityFrameworkCore{
public class DbContext :
    IInfrastructure<IServiceProvider>,
    IDbContextDependencies,
    IDbSetCache,
    IDbContextPoolable
{
    private readonly DbContextOptions _options;

    private IDictionary<(Type Type, string? Name), object>? _sets;
    private IDbContextServices? _contextServices;
    private IDbContextDependencies? _dbContextDependencies;
    private DatabaseFacade? _database;

/// <summary>
    ///     Provides access to database related information and operations for this context.
    /// </summary>
    public virtual DatabaseFacade Database
    {
        get
        {
            CheckDisposed();

            return _database ??= new DatabaseFacade(this);
        }
    }
 }}

I'm injecting DBContext in the ConfigureServices method of Startup.cs, hence I cannot create multiple DBContexts for each thread.我在 Startup.cs 的 ConfigureServices 方法中注入 DBContext,因此我无法为每个线程创建多个 DBContext。

Also, service lifetime for DBContext is set to transient when configuring the context:此外,在配置上下文时,DBContext 的服务生命周期设置为瞬态:

services.AddDbContextFactory<MyQueryDbContext>(options => options.UseSqlServer(MyQuery, sqlServerOptions => sqlServerOptions.CommandTimeout(databaseTimeout)), ServiceLifetime.Transient);

Where MyQueryDbContext looks like this: MyQueryDbContext 看起来像这样:

public class MyQueryDbContext  : MyDbCtx<MyQueryDbContext>, IMyQuery
{
    public MyQueryDbContext(DbContextOptions<MyQueryDbContext> model) : base(model)
    {
    }
}

And here's the MyDbCtx:这是 MyDbCtx:

public class MyDbCtx<TContext> : DbContext
{
    public MyDbCtx(DbContextOptions<TContext> model) : base(model)
    {
    }
}

So, I'm not explicitly overriding OnConfiguring method as I'm providing config details from outside因此,我没有显式覆盖 OnConfiguring 方法,因为我从外部提供配置详细信息

I can make that async method run synchronously but what other options do I have?我可以使该异步方法同步运行,但我还有哪些其他选择?

Resolved after adding the service of the type, which contained the exception-raising method, as 'scoped' in startup.在启动时将包含异常引发方法的类型的服务添加为“作用域”后解决。 Missed that it was being added as singleton错过了它被添加为 singleton

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asp.net core在上一个操作完成之前,在此上下文中启动了第二个操作 - asp.net core A second operation started on this context before a previous operation completed 在前一个操作完成之前,在此上下文上启动了第二个操作 Asp.net EF Core - A second operation started on this context before a previous operation completed Asp.net EF Core ASP.NET 核心标识:在前一个操作完成之前在此上下文上启动了第二个操作 - ASP.NET Core Identity : a second operation started on this context before a previous operation completed 在上一个操作完成ASP NET CORE之前,在此上下文上开始了第二个操作 - A second operation started on this context before a previous operation completed ASP NET CORE ASP Net Core 和实体框架错误 - 在前一个操作完成之前在此上下文中启动了第二个操作 - ASP Net Core and Entity Framework Error - A second operation was started on this context before a previous operation completed ASP.Net MVC 与 LINQ Lambda select 异步导致“在前一个操作完成之前在此上下文上启动了第二个操作。” - ASP.Net MVC async with LINQ Lambda select results in "A second operation was started on this context before a previous operation completed." .Net Core控制台应用程序中的DbContext依赖注入:在上一个操作完成之前,在此上下文中启动了第二个操作 - Dependency Injection of DbContext in .Net Core console app: A second operation started on this context before a previous operation completed UserManager 错误“在上一个操作完成之前,在此上下文中启动了第二个操作” - UserManager error "A second operation started on this context before a previous operation completed" 在先前的异步操作完成之前,在该上下文上开始第二操作 - A second operation started on this context before a previous asynchronous operation completed Blazor:在前一个操作完成之前在此上下文上启动了第二个操作 - Blazor: A second operation started on this context before a previous operation completed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM