1

I have gone through many articles but find too less information about the scope of DbContext in window forms applications. So far I have seen following implementations:

1) First Implementation

using(var db=new DbContext())
{
   // perform operations
}

2) Second Implementation

public class A
{
     private DbContext _db;

     public void DoSomething()
     {
         _db.Students.Find(1);
     }
}

3) Third Implementation

Using the Singleton class to initialize the DbContext and call it in whole program/Application

4) Fourth Implementation

Declaring the DbContext in a common or settings class as a static property and Call it in whole project/Application.

So, my question is what is the best implementation of DbContext in an application and why ? And what are the drawbacks of other implementations that are not the best ?

Mr. Usama
  • 79
  • 1
  • 1
  • 10

1 Answers1

1

DbContext is a unit-of-work pattern and is designed to be (a) cheap to instantiate and (b) short lived.

You can run into a lot of problems using a long-lived DbContext. For example, retrieved entities are cached per DbContext so this can happen: Entity Framework reverts changes

Paul Abbott
  • 6,915
  • 3
  • 25
  • 42
  • So this means that I should go with the first implementation but I have seen many experts using the singleton implementation – Mr. Usama Feb 17 '18 at 05:48