问题描述
我编写了一个 NHibernateSessionFactory 类,它包含一个静态的 Nhibernate ISessionFactory.这用于确保我们只有一个会话工厂,并且第一次调用 OpenSession() 时我创建了实际的 SessionFactory - 下次我使用相同的并在其上打开一个会话.代码如下所示:
I have written an NHibernateSessionFactory class which holds a static Nhibernate ISessionFactory. This is used to make sure we only have one session factory, and the first time OpenSession() is called I create the actuall SessionFactory - next times I use the same and open a session on it. The code looks like this:
public class NhibernateSessionFactory : INhibernateSessionFactory
{
private static ISessionFactory _sessionFactory;
public ISession OpenSession()
{
if (_sessionFactory == null)
{
var cfg = Fluently.Configure().
Database(SQLiteConfiguration.Standard.ShowSql().UsingFile("Foo.db")).
Mappings(m => m.FluentMappings.AddFromAssemblyOf<MappingsPersistenceModel>());
_sessionFactory = cfg.BuildSessionFactory();
BuildSchema(cfg);
}
return _sessionFactory.OpenSession();
}
private static void BuildSchema(FluentConfiguration configuration)
{
var sessionSource = new SessionSource(configuration);
var session = sessionSource.CreateSession();
sessionSource.BuildSchema(session);
}
}
现在我遇到了问题.我的应用程序在客户端和服务器之间拆分.Nhibernate 的东西在服务器端.在启动时,我的客户端和服务器都希望通过一些将使用 NhibernateSessionFactory 的服务访问数据库.结果是 _sessionFactory 是否在请求来自客户端之前创建的竞争条件.如果不是,它将失败..
Now I have a problem. My application is split between client and server. The Nhibernate stuff is on the server side. On startup both my client and server wants to access the database through some services which will use the NhibernateSessionFactory. Result is a race condition to whether the _sessionFactory is created before the request comes from the client. If it isn't it will fail..
我想我需要在 NhibernateSessionFactory 中使用某种排队或等待机制,但我不确定该怎么做.以前有人遇到过同样的问题吗?最好的解决办法是什么?
I guess I need some sort of queueing or wait mechanism in the NhibernateSessionFactory, but I'm not sure about what to do. Anyone had the same problem before? What's the best solution?
推荐答案
sessionFactory
必须是线程安全的单例.
The sessionFactory
must be a thread-safe singleton.
Java 中的一个常见模式是在静态初始化程序中构建 sessionFactory
.请参阅 HibernateUtil.你可以在 C# 中做同样的事情.
A common pattern in Java is to build the sessionFactory
in a static initializer. See HibernateUtil. You can do the same in C#.
还有其他模式来实现单例,包括使用锁或同步部分.如果我理解正确,这里有一些细微的变体,应该可以解决您的问题.
There are other patterns to implement singleton, including the usage of lock or synchronized sections. Here is slight variant that should solve your problem if I understood it correctly.
static readonly object factorylock = new object();
public ISession OpenSession()
{
lock (factorylock)
{
if (_sessionFactory == null)
{
var cfg = Fluently.Configure().
Database(SQLiteConfiguration.Standard.ShowSql().UsingFile("Foo.db")).
Mappings(m => m.FluentMappings.AddFromAssemblyOf<MappingsPersistenceModel>());
_sessionFactory = cfg.BuildSessionFactory();
BuildSchema(cfg);
}
}
return _sessionFactory.OpenSession();
}
这篇关于确保 NHibernate SessionFactory 只创建一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!