4

Fluent NHibernate 用の次の SessionFactory があります。

次のエラーが表示されます

SessionFactory の作成中に、無効または不完全な構成が使用されました。

のInnerExceptionで

同じキーを持つアイテムが既に追加されています。

この問題はたまにしか発生せず、ほとんどの場合、アプリケーションは正常に動作します。

NHibernateに基づく: System.Argument Exception : An item with the same key has already been added私のクラスは、このエラーの断続的な性質を説明するスレッドセーフではないと推測しています。

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;
        }
    }
}
4

1 に答える 1

5

通常のアプローチは、単一のアクセスのみを許可するミューテックスを (おそらく public メソッドで) 作成することです。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;
    }
于 2011-03-18T14:19:10.333 に答える