I want to create a Singleton Object for Database context creation. I am just curious if it good practice to use singleton context in mvc applications.
Can somebody describe the pros and cons for a singleton context object?
I want to create a Singleton Object for Database context creation. I am just curious if it good practice to use singleton context in mvc applications.
Can somebody describe the pros and cons for a singleton context object?
DbContext
is not thread safe which is a massive con for its use as a singleton object in a multithreaded usage environment such as ASP.NET MVC. Multiple concurrent DB operations will result in a thrown exception and you would need to synchronize access to the singleton object to avoid such a scenario. You would also need to worry about stale cached data over its lifetime and manage refreshing said data appropriately.
As a clarification point, consider if your singleton needs to be per session request or app domain. If you limit the scope to a single session request, you could be ok having a single access point (factory) for your variable creation and keep that value alive through that session, but make sure to dispose it when the request is complete.
However, don't keep a single context value alive for the entire app domain (static variable) or even user session. The context remembers every object that it fetched (to support tracking updated fields/values). Eventually you would end up duplicating your database in memory, but only with the values from that server instance. If you have a farm, this would be compounded by stale data between the servers over time.
It is really bad to use singleton DbContex. All changes will be check in each SaveChanges. When your DbContext have lived long enough, it will be verry slow.