I’ve had issues with EF Core when operating with multiple threads and with multiple calls at the same time.
The most important things to check are:
- The DbContext is not being shared between calls or threads
- All classes which have the context inyected must be scoped (not singleton)
- If working with async methods, you need to await calls
I have the following service
public class PersonService(AppDbContext _context)
{
public async Task<Person> GetPerson(string id)
{
return await context.Persons.Find(id);
}
}
which I may configure as follows
// if I inject it as singleton, this would cause exceptions on multiple calls
services.AddSingleton<IPersonService, PersonService>
// we have to inject it as scoped so it creates a context new for each call
services.AddScoped<IPersonService, PersonService>