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?
Managing Lifetime
You’re correct that a single static instance of
DbContextis usually not recommended:These comments apply directly to the
DbContext, because it wraps wrapsObjectContextto expose “simplified and more intuitive APIs.” [see documentation]Cost of Construction
The overhead of creating the context is relatively low:
The common way to work with a short-lived context is to wrap it in a using block:
To ease with testing, you may want to have your
DbContextimplement someIDbContextinterface, and create a factory classContextFactory<T> where T : IDbContextto instantiate contexts.This allows you to easily swap any
IDbContextinto your code (ie. an in-memory context for object mocking.)Resources