简体   繁体   中英

How to update database from another thread

In my Asp.net Core project I am using a Backgroundworker for doing a very timeintensive process. After the worker has finished I want to update the database. The connection to the database is injected via dependency injection.

I get the following error:

System.ObjectDisposedException: "Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. "

The reason is that my mainthread alredy returns an ActionResult before the backgroundworker is finished and that sould be done this way. But the connection to the database is disposed.

Is there now a way to prevent dependency injection from disposing?

I already tried to clone the database connection, but I getting the same error.

Nope. Gratulations. You found a case where using dependency injection to get a database connection does not work. Period. This is part of the design of the flow - DI in ASP:nET Core is tied to the lifetime of the request, and a background worker... is not. Choices?

  • Ask for a separate db connection from DI, directly.
  • start another internal request so the DI stack runs for that one. This one can run synchroneous from the asp.net stack point of view, so the DI does not dispose it.
  • Have an alternative way to get a database connection object WITHOUT the DI mechanism that asp.net core uses for page lifetime access.

There is no way to avoid the disposing as this basically is a fundamental scenario. It is there to clean up after the request.

DId you read https://learn.microsoft.com/en-us/do.net/architecture/microservices/multi-container-microservice.net-applications/background-tasks-with-ihostedservice ? That one talks about implementing micro services internally. This enables the use of dependency injection on those hosted services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM