Does having a share context can cause trouble ? RRS feed

  • Question

  • Dear all,

    I have an SQL server databse that I access through an EF and an ShareContext defined as follow :

    public class SharedObjectContext
            private readonly QuizzEntities context;
            #region Singleton Pattern
            // Static members are lazily initialized.
            // .NET guarantees thread safety for static initialization.
            private static readonly SharedObjectContext instance = new SharedObjectContext();
            // Make the constructor private to hide it. 
            // This class adheres to the singleton pattern.
            private SharedObjectContext()
                // Create the ObjectContext.
                context = new QuizzEntities();
            // Return the single instance of the ClientSessionManager type.
            public static SharedObjectContext Instance
                    return instance;
            public QuizzEntities Context
                    return context;

    This context is used in a global application when data need to be access. So once the context is instanciate once, it will reamain alive.
    Do you think it could cuase trouble  ?

    Or is it better to create the Entities context each time needed ?


    Your knowledge is enhanced by that of others.

    Monday, June 25, 2012 10:08 AM


  • Entity Context is all about caching and tracking. So memory consumption will grow together with context related data manipulation.

    If a Entity Context is never dispose then there could be a memory leak issue, since context is carrying around the references about all related entities. Those will never be collected by GC.

    For my personal experience, Context per request is the best approach to handle all the requests including asynchronous [ajax] requests.

    May be you might consider to use scope based Context for windows environment apps.


    Monday, June 25, 2012 3:32 PM