目前在我们的应用程序中,我们打开每个存储库调用的会话。例如:
using (var session = SessionProvider.Instance.OpenSession())
{
// get or update an entity
}
每次从数据库中需要某些东西时,都会使用上述模式。我们的DBA告诉我们,数据库中正在打开太多连接,我觉得这是罪魁祸首。
我们的会话提供商如下所示:
public static SessionProvider Instance { get; private set; }
public ISessionFactory SessionFactory { get; private set; }
public static string ConnectionStringKey;
static SessionProvider()
{
Instance = new SessionProvider();
}
private SessionProvider()
{
try
{
if (ConnectionStringKey == null)
ConnectionStringKey = ConfigurationManager.AppSettings["hibernate.connection.connection_string_name"];
SessionFactory = CreateSessionFactory();
}
catch (Exception ex)
{
EventLogger.Error("Failed to create NHibernate SessionFactory: " + ex.Message + ": " + ex.StackTrace);
throw; // we should always throw otherwise the error that gets thrown will be confusing e.g: NullReferenceException
}
}
public ISession OpenSession()
{
return SessionFactory.OpenSession();
}
public IStatelessSession OpenStatelessSession()
{
return SessionFactory.OpenStatelessSession();
}
public ISession OpenSession(IDbConnection connection)
{
return SessionFactory.OpenSession(connection);
}
private static ISessionFactory CreateSessionFactory()
{
switch (ConnectionStringKey)
{
// Add more databases here
default:
return MssqlSessionFactory.CreateSessionFactory(ConnectionStringKey);
}
}
想知道是否可以通过用GetCurrentSession()替换OpenSession()来轻松解决这个问题,然后宾果整个app将使用一个连接?