How to fix 'A second operation started on this context before a previous operation completed…' when working with dependency injection?

别说谁变了你拦得住时间么 提交于 2019-12-08 02:38:14

问题


when reading data from the database I get this error:

A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

I have the following ApplicationContext.cs:

public class ApplicationContext : Microsoft.EntityFrameworkCore.DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
    { }

    public DbSet<MyClass> MyClasses{ get; set; }
}   

The following ApplicationContextFactory.cs

public class ApplicationContextFactory : IDesignTimeDbContextFactory<ApplicationContext>
{
    public ApplicationContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<ApplicationContext>();
        var connection = "myConnectionString";

        builder.UseSqlServer(connection);

        return new ApplicationContext(builder.Options);
    }
}   

The following ServiceLoader.cs (where I declare the DI):

public static class ServiceLoader
{
    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IRepository, Repository>();

        var connection = "myConnectionString";
        services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connection));
    }
}

and finally, the following Repository, where the exception is thrown:

public class Repository : IRepository
{
    private ApplicationContext _db;

    public Repository (ApplicationContext db)
    {
        _db = db;
    }

    public List<MyClass> Get()
    {
        _db.MyClasses.ToList();
    }
}

I have also tried to declare the Repository as Transient instead of Singleton, but a similar error is thrown

'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.'

Any idea on how to fix this? Thanks!


回答1:


In my case I found the following information helpful:

https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

And changed the lifetime scope of my Db Context to transient using the overloaded AddDbContext method in startup:

services.AddDbContext<MyAppDbContext>(options => {
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection"));
        }, ServiceLifetime.Transient);



回答2:


You can wrap an async Task around your Get() function and await your results:

public async Task<List<MyClass>> Get()
{
   return await _db.MyClasses.ToListAsync();
}


来源:https://stackoverflow.com/questions/46395150/how-to-fix-a-second-operation-started-on-this-context-before-a-previous-operati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!