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

北慕城南 提交于 2019-12-27 19:13:06

问题


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?


回答1:


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



回答2:


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();
  }
}


来源:https://stackoverflow.com/questions/7647912/why-re-initiate-the-dbcontext-when-using-the-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!