polska amoshen
polska amoshen

Reputation: 35

Is it a bad idea to make ef core DbContext transient?

I have multiple IHostedService instances and each instance according to the time when it springs to action should use DbContext to perform some database works.

Should I use scoped, transient or singleton in this case ?

Thanks in advance.

Upvotes: 3

Views: 3116

Answers (1)

MKougiouris
MKougiouris

Reputation: 2861

It rly comes down to design and architecture, but i would suggest always going on the "Scoped" route.

This will make sure that each new request will receive a new context, but the same context will be used for the same request, meaning that you start to get a "transactional" type of request serving, which is the best thing to do on 99% of the business cases.

If there is a request that i.e:

  1. Assignes a new vehicle to the user
  2. Charches the user's account

then you want the whole business logic within your server request to be "transactional" in respect to the changes of the data. Either both changes will succeed and commit as part of the "business transaction" or non will, leaving you with a clean data-set.

Having them "Transient" risks many concurrency related stuff, especcialy because we are talking for EF context.

Having them "Singleton" could be ok, again with the general architecture of the application and proper handling of dependency injections in mind.

Upvotes: 2

Related Questions