关闭连接后连接池

时间:2012-12-17 18:37:40

标签: nhibernate fluent-nhibernate connection-pooling

我收到maximum pool size reached错误。以下是我的SessionManager

public class FNHsessionManager
{
    private static ISessionFactory _sessionFactory{get;set;}

    //To solve the Threading Issue
    private static Mutex _sessionMutex = new Mutex();

    private static ISessionFactory GetFactory<T>() where T : ICurrentSessionContext
    {
        if (_sessionFactory == null)
            _sessionMutex.WaitOne();
        try
        {
            NHibernate.Cfg.Configuration con = new NHibernate.Cfg.Configuration();
            con.SetProperty("dialect", "NHibernate.Dialect.MsSql2008Dialect");
            con.AddAssembly("arc.alert");
            _sessionFactory = Fluently.Configure(con).Database(MsSqlConfiguration.MsSql2008.ConnectionString(ConfigurationManager.ConnectionStrings["ArcAlertConnectionString"].ConnectionString)
                .ShowSql())
            .CurrentSessionContext<T>()
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Alert>())
            .BuildSessionFactory();
        }
        catch (System.Exception)
        {
            throw;
        }
        finally
        {
            _sessionMutex.ReleaseMutex();
        }
        return _sessionFactory;
    }



    public static ISession Session()
    {
        if (_sessionFactory == null)
            _sessionFactory = HttpContext.Current != null
                            ? GetFactory<WebSessionContext>()
                            : GetFactory<ThreadStaticSessionContext>();
        if (CurrentSessionContext.HasBind(_sessionFactory))
            return _sessionFactory.GetCurrentSession();
        ISession session = _sessionFactory.OpenSession();
        CurrentSessionContext.Bind(session);
        return session;
    }

    public static void CloseSession()
    {
        if (_sessionFactory == null)
            return;
        if (CurrentSessionContext.HasBind(_sessionFactory))
        {
            ISession session = CurrentSessionContext.Unbind(_sessionFactory);
            if (session.IsOpen)
            {
                session.Close();
            }
        }
    }

    public static void CommitSession(ISession session)
    {
        try
        {
            session.Transaction.Commit();
        }
        catch (Exception)
        {
            session.Transaction.Rollback();
            throw;
        }
    }
}
}

然后,每次打开会话时,我都会在CloseSession()块中调用finally{}方法。

当我上传新的DLL时,我经常会遇到connection timeout错误。但是,在一两天之后,我将此错误的时间减少到每天一次。

我做错了什么?

0 个答案:

没有答案