This error is caused by you using the same DbContext
instance on multiple threads at the same time. This is generally a scoping issue. I don't see in the code you posted where it is making any use of the DB context so it is hard to say where the problem is at this point. Confirm that every use of the context is from the same DI type you configured. Also I notice that you're using transient scope here which is probably not correct. Transient means every request gets a new copy. Thus if your repos each request the DbContext
they will end up getting different copies of the type which means they cannot interact with potentially shared data. In general you should prefer AddScoped
unless you need a new instance each time the call is made.
It can also happen if you are using a single DbContext
instance but in the middle of it being used (such as a deferred LINQ call), you then start another query that requires it to connect to the DB again. Since the first query is still in progress it cannot allow another connection. This is harder to recognize in code because we have no way of knowing how the queries might interact at runtime. One scenario I've seen it happen is when enumerating a resultset and lazy loading is triggered after the query has been run on the database but while it is still enumerating the results. The connection cannot be reused because it is still reading the data.