Entity Framework Core and Multithreading

In my ASP.NET Core application, I have complex business logic that includes several threads that perform operations on a database outside the scope of an HTTP request. Access to the database from the same thread processing is trivial, but when threads arise that require their own DbContext, this is tedious. Since the DbContext itself is not thread safe, I tried to create a new DbContext along with my options in addition to getting the DbContext from IServiceProvider. With both approaches, I get the following exception:

An attempt was made to use a context while setting it up. The DbContext instance cannot be used inside OnConfiguring, because it is still configurable at this point.

I get the impression that I am not approaching this problem correctly and that I should not handle such database connections. How can I then get a DbContext in a separate thread from one processing incoming requests?

+5
source share
1 answer

It turned out that my test code had a small typo, thanks to which it used the same DbContext for all threads. However, I need to create a new instance of DbContext, but I cannot get it through IServiceProvider, as mentioned in my question.

-1
source

All Articles