我们正在与一组基本上无法改变的相同结构的遗留数据库进行不同的集成.为此,我们添加了一个辅助数据库,用于保存元信息,路由规则和临时保存旧数据库数据等内容.
我们主要使用NHibernate连接数据库.一个应用程序是WCF服务,需要将传入的数据插入到非常宽的嵌套表中(数十列).显然,性能是一个问题,所以我一直希望NHibernate事务尽可能经济.与此同时,并发似乎是一个问题.在生产中,我们开始遇到一些僵局的事务错误(死锁).
我一直在做一个处理这两个问题的平衡行为,但并没有真正消除并发问题.
服务行为设置为一次处理一个请求,如下所示:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode=ConcurrencyMode.Single]
public class LegacyGateService : ILegacyGateService
Run Code Online (Sandbox Code Playgroud)
早些时候,在从互联网上获得一些"灵感"(阅读:复制/粘贴)之后,我最终分别为辅助数据库和遗留数据库添加了一组名为XxxNHibernateUtil的类.这些类控制NHibernate会话,并从预先初始化的SessionFactories生成或重用Sessions.
对于辅助数据库,它看起来像这样:
public static class LegacyGateNHibernateUtil
{
private static readonly ISessionFactory sessionFactory = BuildSessionFactory();
private static ISessionFactory BuildSessionFactory()
{
try
{
Configuration Cfg = new Configuration();
Cfg.Configure();
Cfg.AddAssembly("LegacyGate.Persistence");
return Cfg.BuildSessionFactory();
}
catch (Exception ex)
{
throw ex;
}
}
public static ISessionFactory GetSessionFactory()
{
return sessionFactory;
}
public static ISession GetCurrentSession()
{
if (!CurrentSessionContext.HasBind(GetSessionFactory()))
CurrentSessionContext.Bind(GetSessionFactory().OpenSession());
return GetSessionFactory().GetCurrentSession();
}
public static void DisposeCurrentSession()
{
ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory()); …Run Code Online (Sandbox Code Playgroud)