0

I have always used my db connection as a singleton, thinking that it was faster or using less resources.

My ASP.NET MVC projects will have one instance of my EntityFramework Context that is handed to my controllers via Dependency injection or other means.

But is this worth it or even necessary to have my database context singelton, or would it be the same if I as an example have a instance of my context in one or more action filters and then one or more in my controllers?

Edit: When I say singleton, I mean singleton per request.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Androme
  • 2,399
  • 4
  • 43
  • 82

1 Answers1

3

You should never, never have a singleton for your database connection and/or data context.

Not only this just won't work in a concurrent environment (asp.net) but a single instance of your context that maintains an internal map of entities will take more and more amount of memory leading to a crash sooner or later when working with large database.

But the opposite - have a new instance everywhere - is also a waste. In asp.net yet another lifetime policy is the most suitable: the "per http context" lifetime policy. According to this policy you create a single instance of the data context per each single request and dispose the data context as long as the request completes.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • I'd say you _always_ dispose of the data context _as soon as possible_ - not just with the clause of "as the request completes." The request should technically always complete, but the data context disposal shouldn't rely on this unrelated notion. – Grant Thomas Sep 02 '13 at 08:32
  • @WiktorZychla thank you, i forgot to add in my first post, that when i say singleton, i mean singleton pr request. – Androme Sep 02 '13 at 08:46