When should I create a new DbContext()

C#asp.net MvcEntity Frameworkasp.net Mvc-4

C# Problem Overview


I am currently using a DbContext similar to this:

namespace Models
{
    public class ContextDB: DbContext
    {
              
        public DbSet<User> Users { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }

        public ContextDB()
        {
            
        }
    }
}

I am then using the following line at the top of ALL my controllers that need access to the database. Im also using it in my UserRepository Class which contains all methods relating to the user (such as getting the active user, checking what roles he has, etc..):

ContextDB _db = new ContextDB();

Thinking about this, there are occasions when one visitor can have multiple DbContexts active, for instance if it is visiting a controller that uses the UserRepository, which might not be the best of ideas.

When should I make a new DbContext? Alternatively, should I have one global context that is passed around and reused in all places? Would that cause a performance hit? Suggestions of alternative ways of doing this are also welcome.

C# Solutions


Solution 1 - C#

I use a base controller that exposes a DataBase property that derived controllers can access.

public abstract class BaseController : Controller
{
    public BaseController()
    {
        Database = new DatabaseContext();
    }

    protected DatabaseContext Database { get; set; }

    protected override void Dispose(bool disposing)
    {
        Database.Dispose();
        base.Dispose(disposing);
    }
}

All of the controllers in my application derive from BaseController and are used like this:

public class UserController : BaseController
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(Database.Users.OrderBy(p => p.Name).ToList());
    }
}

Now to answer your questions:

> When should I make a new DbContext / should I have one global context > that I pass around?

The context should be created per request. Create the context, do what you need to do with it then get rid of it. With the base class solution I use you only have to worry about using the context.

Do not try and have a global context (this is not how web applications work).

> Can I have one global Context that I reuse in all places?

No, if you keep a context around it will keep track of all the updates, additions, deletes etc and this will slow your application down and may even cause some pretty subtle bugs to appear in your application.

You should probably chose to either expose your repository or your Context to your controller but not both. Having two contexts being access from the same method is going to lead to bugs if they both have different ideas about the current state of the application.

Personally, I prefer to expose DbContext directly as most repository examples I have seen simply end up as thin wrappers around DbContext anyway.

> Does this cause a performance hit?

The first time a DbContext is created is pretty expensive but once this has been done a lot of the information is cached so that subsequent instantiations are a lot quicker. you are more likely to see performance problems from keeping a context around than you are from instantiating one each time you need access to your database.

> How is everyone else doing this?

It depends.

Some people prefer to use a dependency injection framework to pass a concrete instance of their context to their controller when it is created. Both options are fine. Mine is more suitable for a small scale application where you know the specific database being used isn't going to change.

some may argue that you can't know this and that is why the dependency injection method is better as it makes your application more resilient to change. My opinion on this is that it probably won't change (SQL server & Entity Framework are hardly obscure) and that my time is best spent writing the code that is specific to my application.

Solution 2 - C#

I try to answer out of my own experience.

1. When should I make a new DbContext / should I have one global context that I pass around?

The Context should be injected by the dependency-injection and should not be instantiated by yourself. Best-Practice is to have it created as a scoped service by the dependency-injection. (See my answer to Question 4)

Please also consider using a proper layered application structure like Controller > BusinessLogic > Repository. In this case it would not be the case that your controller receives the db-context but the repository instead. Getting injected / instantiating a db-context in a controller tells me that your application architecture mixes many responsibilities in one place, which - under any circumstances - I cannot recommend.

2. Can i have one global Context that I reuse in all places?

Yes you can have but the question should be "Should I have..." -> NO. The Context is meant to be used per request to change your repository and then its away again.

3. Does this cause a performance hit?

Yes it does because the DBContext is simply not made for being global. It stores all the data that has been entered or queried into it until it is destroyed. That means a global context will get larger and larger, operations on it will get slower and slower until you will get an out of memory exceptions or you die of age because it all slowed to a crawl.

You will also get exceptions and many errors when multiple threads access the same context at once.

4. How is everyone else doing this?

DBContext injected through dependency-injection by a factory; scoped:

services.AddDbContext<UserDbContext>(o => o.UseSqlServer(this.settings.DatabaseOptions.UserDBConnectionString));

I hope my answers where of help.

Solution 3 - C#

In performance point of view, DbContext should be created just when it is actually needed, For example when you need to have list of users inside your business layer,you create an instance form your DbContext and immediately dispose it when your work is done

using (var context=new DbContext())
{
    var users=context.Users.Where(x=>x.ClassId==4).ToList();
}

context instance will be disposed after leaving Using Block.

But what would happen if you do not dispose it immediately?
DbContext is a cache in the essence and the more you make query the more memory blocks will be occupied.
It will be much more noticeable in case of concurrent requests flooding towards your application, in this case,each millisecond that you are occupying a memory block would be of the essence, let alone a second.
the more you postpone disposing unnecessary objects the more your application is closed to crash!

Of course in some cases you need to preserve your DbContext instance and use it in another part of your code but in the same Request Context.

I refer you to the following link to get more info regarding managing DbContext:
dbcontext Scope

Solution 4 - C#

You should dispose the context immediately after each Save() operation. Otherwise each subsequent Save will take longer. I had an project that created and saved complex database entities in a cycle. To my surprise, the operation became three times faster after I moved

using (var ctx = new MyContext()){...}

inside the cycle.

Solution 5 - C#

Right now I am trying this approach, which avoids instantiating the context when you call actions that don't use it.

public abstract class BaseController : Controller
{
    public BaseController() { }

    private DatabaseContext _database;
    protected DatabaseContext Database
    {
        get
        {
            if (_database == null)
                _database = new DatabaseContext();
            return _database;
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (_database != null)
            _database.Dispose();
        base.Dispose(disposing);
    }
}

Solution 6 - C#

This is obviously an older question but if your using DI you can do something like this and scope all your objects for the lifetime of the request

 public class UnitOfWorkAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var context = IoC.CurrentNestedContainer.GetInstance<DatabaseContext>();
            context.BeginTransaction();
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionContext)
        {
            var context = IoC.CurrentNestedContainer.GetInstance<DatabaseContext>();
            context.CloseTransaction(actionContext.Exception);
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJensBView Question on Stackoverflow
Solution 1 - C#Benjamin GaleView Answer on Stackoverflow
Solution 2 - C#RaviorView Answer on Stackoverflow
Solution 3 - C#AbolfazlView Answer on Stackoverflow
Solution 4 - C#Gregory KhrapunovichView Answer on Stackoverflow
Solution 5 - C#AndrewView Answer on Stackoverflow
Solution 6 - C#CSharperView Answer on Stackoverflow