Entity Framework Context in Singleton

孤人 提交于 2019-12-03 08:46:53
Ladislav Mrnka

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.

A good pratice is to use a datacontext per unit of work To have more information about unit of work with EF you should read http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx

When sharing the same datacontext you are probably saving a few 10s of milliseconds. The word micro optimisation springs to mind - in which case you probably shouldn't be using Entity Framework.

Having a DataContext that is never closed allows you to lazy load whenever you want. You may have left your Service and now be in your Controller or worse still, your View. Accessing the database from a View is asking for performance problems as I'm sure you didn't allow that intentionally. It is most likely because you forgot to eager load all the data you need to populate your view.

You read this article. Why you shouldn't use singleton DataContexts in Entity Framework? http://www.britishdeveloper.co.uk/2011/03/dont-use-singleton-datacontexts-entity.html

public class Dock
{
    // Statik field
    private static Dock _dock;
    // lock object
    private static object lockObject = new object();

    // We prevent the constructive method from being modeled with new by 
    //making it secret.
    private Dock()
    {

    }
    // Class in Instance
    public static Dock Instance()
    {   
        if (_dock == null)
        {
            lock (lockObject)
            {
                if (_dock == null)
                    _dock = new Dock();
            }
        }
        return _dock;
    }

}

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