首页 > 解决方案 > System.InvalidOperationException:不能在 OnConfiguring 内部使用 DbContext 实例,因为此时它仍在配置中

问题描述

在我的应用程序中进行负载测试时遇到以下错误。从邮递员进行负载测试时不会出现此错误。谁能帮我解决这个问题。我不知道这里出了什么问题。

在配置上下文时尝试使用上下文。DbContext 实例不能在 OnConfiguring 中使用,因为此时它仍在配置中。如果在前一个操作完成之前对此上下文启动了第二个操作,则可能会发生这种情况。不保证任何实例成员都是线程安全的。

   // Service regisered in Startup.cs
   services.AddTransient<IExceptionHandlerService, ExceptionHandlerService>();
    
   // Calling the below method like this
   return exceptionHandler.LogRequestAsync(log);
    
   // LogRequestAsync method inside ExceptionHandlerService class is 
   // throwing this error

   public class ExceptionHandlerService : IExceptionHandlerService
   {

    private ConnectionStrings _connectionStrings;
    private myapp_myappContext dbContext;

    public ExceptionHandlerService(IOptions<ConnectionStrings> connectionStrings)
    {
        _connectionStrings = connectionStrings.Value;
        dbContext = new myapp_myappContext(_connectionStrings);
    }

    // This method is throwing error. This method was not async earlier. 
    // I made this async due to the above error but still, 
    // the result is the same.
    public async Task<int> LogRequestAsync(RequestLogDto model)
    {
        try
        {
            var log = new MyappRequestlog()
            {
                Ipaddress = model.Ipaddress,
                UserId = model.UserId,
                Url = model.Url,
                MethodType = model.MethodType,
                Urlreferrer = model.Urlreferrer,
                Browser = model.Browser,
                Device = model.Device,
                RequestBody = model.RequestBody,
                Response = model.Response,
                ExceptionMessage = model.ExceptionMessage,
                StackTrace = model.StackTrace,
                CreatedDate = DateTime.Now
            };
            dbContext = new myapp_myappContext(_connectionStrings);
            await dbContext.MyappRequestlog.AddAsync(log);
            await dbContext.SaveChangesAsync();
            return log.LogId;
        }
        catch (Exception ex)
        {
            string strFilePath = ApplicationVariables.ErrorFilePath;
            if (!string.IsNullOrEmpty(strFilePath))
            {
                File.AppendAllLines(strFilePath, new[] { $"{ex}. Error generate datetime : {DateTime.Now}" });
            }
            return 0;
        }
    }

    public virtual DbSet<MyappExternalcalllog> MyappExternalcalllog { get; set; }

    // This is OnConfiguringmethod which the error is indicating
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseMySql(_connectionStrings.DefaultConnection);
        }
    }


    // This method is saving data in database
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder.Entity<MyappRequestlog>(entity =>
        {
            entity.HasKey(e => e.LogId);

            entity.ToTable("myapp_requestlog");

            entity.Property(e => e.LogId).HasColumnType("int(11)");

            entity.Property(e => e.Browser).HasColumnType("varchar(1000)");

            entity.Property(e => e.CreatedDate).HasColumnType("datetime");

            entity.Property(e => e.Device).HasColumnType("varchar(15)");

            entity.Property(e => e.ExceptionMessage).HasColumnType("text");

            entity.Property(e => e.Ipaddress)
                .HasColumnName("IPAddress")
                .HasColumnType("varchar(25)");

            entity.Property(e => e.MethodType).HasColumnType("varchar(9)");

            entity.Property(e => e.RequestBody).HasColumnType("text");

            entity.Property(e => e.Response).HasColumnType("text");

            entity.Property(e => e.StackTrace).HasColumnType("text");

            entity.Property(e => e.Url)
                .HasColumnName("URL")
                .HasColumnType("text");

            entity.Property(e => e.Urlreferrer)
                .HasColumnName("URLReferrer")
                .HasColumnType("text");

            entity.Property(e => e.UserId).HasColumnType("varchar(38)");
        });
     }

// 以下是此错误的堆栈跟踪

System.InvalidOperationException: 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.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at MyApp.LoggerService.ExceptionHandlerService.LogRequest(RequestLogDto model) in D:\My API and Application TFS\My API\WebAPICore\MyAPI_V2\MyApp.LoggerService\ExceptionHandlerService.cs:line 47. Error generate datetime : 07/07/2020 10:41:26
System.InvalidOperationException: 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.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity)
   at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
   at MyApp.LoggerService.ExceptionHandlerService.LogRequest(RequestLogDto model) in D:\My API and Application TFS\My API\WebAPICore\MyAPI_V2\MyApp.LoggerService\ExceptionHandlerService.cs:line 47. Error generate datetime : 07/07/2020 10:41:26
System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at MyApp.LoggerService.ExceptionHandlerService.LogRequest(RequestLogDto model) in D:\My API and Application TFS\My API\WebAPICore\MyAPI_V2\MyApp.LoggerService\ExceptionHandlerService.cs:line 47. Error generate datetime : 07/07/2020 10:41:27
System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList`1 entriesToSave)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
   at MyApp.LoggerService.ExceptionHandlerService.LogRequest(RequestLogDto model) in D:\My API and Application TFS\My API\WebAPICore\MyAPI_V2\MyApp.LoggerService\ExceptionHandlerService.cs:line 47. Error generate datetime : 07/07/2020 10:41:27

标签: .net-coreasync-awaitentity-framework-coredbcontextinvalidoperationexception

解决方案


推荐阅读