Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 327
joacoleza Avatar asked Sep 24 '17 21:09

joacoleza


1 Answers

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);
like image 72
Rob Avatar answered Nov 14 '22 22:11

Rob