Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Context in Singleton

I'm building a App that use Context of EF in Singleton Pattern like NHibernate work with Session:

public class DbContextFactory
{
    private static volatile DbContextFactory _dbContextFactory;
    private static readonly object SyncRoot = new Object();
    public DbContext Context;

    public static DbContextFactory Instance
    {
        get
        {
            if (_dbContextFactory == null)
            {
                lock (SyncRoot)
                {
                    if (_dbContextFactory == null)
                        _dbContextFactory = new DbContextFactory();
                }
            }
            return _dbContextFactory;
        }
    }

    public DbContext GetOrCreateContext()
    {
        if (this.Context == null)
            this.Context = new DbContext(ConfigurationManager.AppSettings["DefaultConnectionString"]);

        return Context;
    }
}

I'm using Ninject to Inject the Context:

public class DbContextModule : NinjectModule
{
    public override void Load()
    {
        Bind<IDbContext>().ToConstant(DbContextFactory.Instance.GetOrCreateContext());
    }
}

I'm reading about that approach and some people are saying that is bad practice and I'll have problems.

Someone that know about this with EF can explain me in more details?

like image 715
Acaz Souza Avatar asked Dec 07 '25 06:12

Acaz Souza


1 Answers

NHibernate doesn't use Session as singleton ... Such scenario has only meaning in very rare cases where your application is very short batch representing single transaction / unit of work.

Here are described reasons why you should not use shared / long living context. In case of multithreaded or server application serving multiple clients you must not use shared context.

like image 100
Ladislav Mrnka Avatar answered Dec 08 '25 19:12

Ladislav Mrnka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!