我有以下用于 Fluent NHibernate 的 SessionFactory。
我收到一个错误
创建 SessionFactory 时使用了无效或不完整的配置。
带有 InnerException 的
已添加具有相同密钥的项目。
这个问题只是偶尔发生,我的应用程序大部分时间都工作正常。
基于NHibernate:System.Argument异常:已添加具有相同键的项目 https://stackoverflow.com/questions/4855149/nhibernate-system-argument-exception-an-item-with-the-same-key-has-already-bee我猜我的类不是线程安全的,这可以解释这个错误的间歇性。
using System;
using NHibernate;
using NHibernate.Cache;
using NHibernate.Cfg;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using WSS.Data.Domain;
namespace WSS.Data {
public static class SessionFactory {
private static ISessionFactory _factory = null;
private static ISessionFactory GetFactory() {
if (_factory == null) {
NHibernate.Cfg.Configuration config;
config = new NHibernate.Cfg.Configuration();
config.Configure();
if (config == null) {
throw new InvalidOperationException("NHibernate configuration is null.");
}
config.AddAssembly("WSS.Data");
_factory = config.BuildSessionFactory();
if (_factory == null) {
throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
}
}
return _factory;
}
private static ISessionFactory GetFluentFactory() {
if(_factory == null) {
_factory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2000
.ConnectionString(c => c
.Is(ConnectionStrings.Auto))
.Cache(c => c
.UseQueryCache()
.ProviderClass())
.ShowSql())
.Mappings(m => m
.FluentMappings.AddFromAssemblyOf())
.BuildSessionFactory();
}
return _factory;
}
public static ISession OpenSession() {
ISession session;
session = GetFluentFactory().OpenSession();
if (session == null) {
throw new InvalidOperationException("Call to factory.OpenSession() returned null.");
}
return session;
}
}
}
通常的方法是创建一个只允许单次访问的互斥锁(可能在您的公共方法中)。看http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx
没有经过编译测试,但类似:
private static Mutex _sessionMutex = new Mutex();
public static ISession OpenSession() {
ISession session;
_sessionMutex.WaitOne();
session = GetFluentFactory().OpenSession();
if (session == null) {
throw new InvalidOperationException("Call to factory.OpenSession() returned null.");
}
_sessionMutex.ReleaseMutex();
return session;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)