Why re-initiate the DbContext when using the Entity Framework?

Managing Lifetime

You’re correct that a single static instance of DbContext is usually not recommended:

The more you use an ObjectContext, generally the bigger it gets.
This is because it holds a reference to all the Entities it has ever
known about, essentially whatever you have queried, added or attached.
So you should reconsider sharing the same ObjectContext indefinitely.

These comments apply directly to the DbContext, because it wraps wraps ObjectContext to expose “simplified and more intuitive APIs.” [see documentation]


Cost of Construction

The overhead of creating the context is relatively low:

The reality is this cost is actually pretty low, because mostly it
simply involves copying, by reference, metadata from a global cache
into the new ObjectContext. Generally I don’t think this cost is worth worrying about …

The common way to work with a short-lived context is to wrap it in a using block:

using(DbContext context = new SomeDbContext())
{
    // Do work with context
}

To ease with testing, you may want to have your DbContext implement some IDbContext interface, and create a factory class ContextFactory<T> where T : IDbContext to instantiate contexts.

This allows you to easily swap any IDbContext into your code (ie. an in-memory context for object mocking.)


Resources

  • MSDN: How to decide on a lifetime for your ObjectContext
  • StackOverflow: Instantiating a context in LINQ to Entities

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)