我尝试了一种简单而天真的方式,至少目前看来是可行的。我在这里做的有什么根本性的错误吗?当线程退出时,这些变量会被垃圾收集吗?
public static class SessionManager
{
[ThreadStatic]
private static IDictionary<ISessionFactory, ISession> _sessions;
public static ISession GetSession(Type type)
{
var burrow = new BurrowFramework();
if (burrow.WorkSpaceIsReady)
{
return burrow.GetSession(type);
}
else
{
if (_sessions == null)
{
_sessions = new Dictionary<ISessionFactory, ISession>();
}
var factory = burrow.GetSessionFactory(type);
if (!_sessions.ContainsKey(factory))
{
_sessions[factory] = null;
}
var session = _sessions[factory];
if (session == null || !session.IsOpen)
{
session = _sessions[factory] = factory.OpenSession();
}
return session;
}
}
}