0

I'm working with .NET 6 console app. I have Program.cs where the DBContext is instantiated.

public class Program
{
    static ProcedureService procservice;

    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        string onlineConnectionString = "Server = localhost; Database = DB; Trusted_Connection = True;";

        services.AddDbContext<DBContext>(o => o.UseSqlServer(ConnectionString), ServiceLifetime.Transient);
        services.AddScoped<ProcedureService , ProcedureService>();
        var serviceProvider = services.BuildServiceProvider();
        procservice = serviceProvider.GetService<ProcedureService>();
    }
}

I also have an internal class that would call another service to do the logic and save something on the DB.

the service looks like this

public class Service
{
    ProcedureService procservice;

    public Service(ProcedureService procservice)
    {
        this.procservice = procservice;
    }
}

and inside this service I have a method who also calls the ProcedureService and that's the time I had encounter "A second operation was started on this context instance before a previous operation completed."

ProcedureService

public ProcedureService(DBContext context)
    {
        this.context = context;
    }
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
qqrrrr
  • 575
  • 2
  • 8
  • 22
  • change from `ServiceLifetime.Transient` to `ServiceLifetime.Scopped` – Vivek Nuna Dec 23 '22 at 12:10
  • This error means you are using same instance of DbContext concurrently, either from multiple threads, or from the same thread but without awaiting asynchronous operations. – Evk Dec 23 '22 at 12:22
  • why are you not injecting `DBContext` through constructor in class `ProcedureService ?' – Vivek Nuna Dec 23 '22 at 12:23
  • There is not enough information to diagnose what is happening here. You can use the same instance of `DbContext` concurrently which will lead to he described behaviour. Or do something like was done [here](https://stackoverflow.com/a/74892134/2501279). Please share the code showing the `DbContext` usage where the exception is thrown. – Guru Stron Dec 23 '22 at 12:29

0 Answers0