Take the 2-minute tour ×

I've deployed an MVC App on IIS 7.5 that uses EF 4.0. The EF context is encapsulated in a singleton that is shared throughout the app. I did that because I thought that the app needed a single context to manage CRUD functions across all sessions.

This seems to work fine except I've got two issues that are plaguing me:

  1. I find duplicate records in the database occasionally. Note: I don't update records, I mark old records as deleted and write a new record to the DB.

  2. Occasionally, EF looses the SQL Connection causing the entire application to crash, forcing me to recycle the app-pool.

Is it likely that these issues are caused by sharing the context? Would it be better not to use the singleton pattern for EF's context? Does using a singleton create a single point of failure for all Ajax requests from all users?

Thanks for any guidance...

  public class SharedNHREntitiesContext

{ private readonly NHREntities _context;

// Static members are lazily initialized.
// .NET guarantees thread safety for static initialization.
private static readonly SharedNHREntitiesContext instance = new SharedNHREntitiesContext();

// Make the constructor private to hide it.
// This class adheres to the singleton pattern.
private SharedNHREntitiesContext()
  // Create the ObjectContext.
  _context = new NHREntities();

// Return the single instance of the ClientSessionManager type.
public static SharedNHREntitiesContext Instance
    return instance;

public NHREntities Context
    return _context;


share|improve this question
Remember that ObjectContext is not thread safe. –  Pawel Feb 15 '12 at 17:58
Thanks for the references Brad. –  Weej Feb 15 '12 at 18:08
I didn't know context was not thread safe... that's a real problem. Thanks Pawel. –  Weej Feb 15 '12 at 18:09
Not really a problem considering it should be per web request. I am no EF expert but we use ISession in nHibernate with a per web request lifetime –  CrazyCoderz Feb 15 '12 at 18:14

1 Answer 1

Just to follow up: I removed the singleton EF context from the code. I have not had any errors in the week since I did that... so, it seems a singleton context is not a good idea across invocations of the MVC controller.

That being said, I am still getting occasional duplicate rows so I still have some issues to resolve that don't involve the singleton.

Thanks to all those who helped me resolve this.

share|improve this answer

Your Answer


