skip to Main Content

I want to access db mongo/SQL Server in the most effective way.

From my perspective, I will just use context as singleton and that’s all.

I worked before at a company where they use all the logic services as singleton but all the inside db connection made one time like :

using var db = new DBContext("DBName");

So why to work like that if I can use a singleton?

2

Answers


  1. A DbContext is not a database connection. A DbContext will open and close database connections as needed. Your DbContext can be a singleton only if

    1. Your application guarantees that it’s only accessed by one thread at a time.

    2. You manage the Change Tracker to keep it from growing over time, eg with ChangeTracker.Clear.

    The DbContext is intended to be scoped to a Unit-of-work in your application. In Win Forms, WCF, or Console app it’s possible to do this. In any kind of web app it’s not really feasible.

    Login or Signup to reply.
  2. DbContext, DbConnection, MongoDb or RavendDB Session, all these kind of things should be scoped. They may not be singleton for a simple reason: they are not thread safe. Singleton services must be thread safe.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search