3

Say I have a long-running process (e.g. Windows service) which needs to access a database from multiple threads.

DbContext is not thread safe, also it is a good idea not to keep it around for a long time (seems that an accepted best practice in the web environment is to create a new context for each request).

Based on EF docs, Contexts are expected to be short-lived and discarded, and as such have been implemented to be very lightweight and reutilize metadata whenever possible, so it seems like creating a new DB context for each database operation might be a way to go under these circumstances, but it does seem a bit excessive.

Thoughts?

Evgeni
  • 3,341
  • 7
  • 37
  • 64

1 Answers1

0

Short-running, for sure, but not only because of DB considerations, also because of application architecture: if your architecture is Clean Code (as per Bob Martin), a Website or Windows Service would not know anything about the database, they would simply create an Application Service as & when required. The Application Service(s) should be responsible for controlling the lifecycle of the database session, and all the bits they get from it. Works really well for me.

Chalky
  • 1,624
  • 18
  • 20
  • 1
    Why should an application know more about the database when the context lives longer? You only shift the problem from context life cycle to Application Service life cycle. I don't think the context's lifespan itself has any bearing on separation of concerns. – Gert Arnold Jan 11 '18 at 12:31