37

I don't know if there is a better way to use the DbContext because it is not recommended to set is as static when working with WCF. So we are creating it each time we want to access the database.

Knowing all the advantages of using Entity Framework, some become useless since we are recreating the DbContext each time; and more may cause overhead since the process of creating big entity models is to be considered.

What is your opinion?

Rob
  • 5,223
  • 5
  • 41
  • 62
Boomer
  • 1,468
  • 1
  • 15
  • 19
  • Would anyone care to comment on the idea of passing a single instance DataContext as a ref param to all the various methods that need to work with it for that particular transaction? That way, different objects can add/remove entities from it, and in the end, the Context object can update itself after all modifications are done. – Graham Oct 04 '11 at 13:58
  • 2
    @Graham: A `DataContext` still tracks changes made to retrieved "entities" and maintains an identity cache that guarantees that entities retrieved more than one time are represented by using the same object instance. It is also lightweight and is not expensive to create. See http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx – Rob Oct 04 '11 at 20:16
  • @Graham: What this means is that persisting a single instance `DataContext` for your application lifetime could be a bad idea. From the article in my answer: *"If you have a natural finite lifetime way of managing an ObjectContext, such as a short lived Form, a UnitOfWork or a Repository, then scoping the ObjectContext accordingly might be the best thing to do."* – Rob Oct 04 '11 at 20:22
  • You can find cost of creating DbContext here: http://stackoverflow.com/questions/1671334/performance-cost-of-creating-objectcontext-in-every-method-in-entity-framework-v/37408810#37408810 – Matas Vaitkevicius May 27 '16 at 04:40

2 Answers2

56

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

Community
  • 1
  • 1
Rob
  • 5,223
  • 5
  • 41
  • 62
  • Thanks for the additional Info. So, should we use EF in such case? where for example ADO.net could handle basic DB functionalities. Or is it because of the development speed we can get from EF? – Boomer Oct 04 '11 at 13:19
  • 1
    Technically EF is part of ADO.NET, albeit an additional abstraction layer for ORM. I personally enjoy working in EF because of strong typing and LINQ. I would argue that classic DataSets are much less flexible. Also see: http://stackoverflow.com/questions/5268546/ado-net-or-entity-framework-in-visual-studio-2008 – Rob Oct 04 '11 at 13:29
  • "To ease with testing, you may want to have your DbContext implement some IDbContext interface" - I was leaning in this direction. Thanks for confirming. – Jacobs Data Solutions Aug 21 '15 at 13:28
  • For someone using AddDbContext and DI, you can profit from the host.Services.CreateScope() method. The DbContext is Scoped by default, so if you are using anything other than a WebApp (a WebJob for example), just create a new scope and get the DB context from there. You'll have a new one each time you create a new scope. – carraua Oct 16 '20 at 11:48
1

The best practice for webdevelopment seems to be "one context per web request", see Proper Session/DbContext lifecycle management, when working with WCF this could be translated into one context per operation (i.e. one context per WCF method call).

There are different ways to achieve this but one solution, probably not recommended for different reasons, is to create a new instance of the context and pass it to the constructor of your business class:

public void WCFMethod()
{
  using (DBContext db = new DBContext())
  {
    BusinessLogic logic = new BusinessLogic(db);
    logic.DoWork();
  }
}
mrplatina
  • 239
  • 4
  • 7