单体中的实体框架上下文 [英] Entity Framework Context in Singleton

查看:112
本文介绍了单体中的实体框架上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]);

返回上下文;
}
}

我正在使用Ninject注入上下文: / p>

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

我正在阅读这种方法,有些人是说这是不好的做法,我会有问题。



有人知道这与EF可以解释我更多的细节?

解决方案

NHibernate不使用Session作为单例...这种场景只有在非常罕见的情况下,您的应用程序是非常短的批量代表单个事务/工作单元的意义。



这里是描述原因为什么你不应该使用共享/长期的生活环境。在多线程或服务器应用程序为多个客户端服务的情况下,您不得使用共享上下文。


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?

解决方案

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.

这篇关于单体中的实体框架上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆