我正在构建一个应用程序,使用EF的上下文以单例模式工作,就像NHibernate使用会话一样:
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;
}
}
我正在使用Ninject来注入上下文:
public class DbContextModule : NinjectModule
{
public override void Load()
{
Bind<IDbContext>().ToConstant(DbContextFactory.Instance.GetOrCreateContext());
}
}
我正在了解这种方法,有些人说这是不良做法,可能会导致问题。
有了解EF的人能否详细解释一下呢?