我对这些技术还很陌生。这里真正的问题是如何在控制台应用程序中管理每个线程的会话。目前,如果我将它作为单个线程运行,那么一切都很顺利。一旦我切换到多线程模型,我将开始在会话级别看到争用(因为Session对象不是设计上的安全性)KeyNotFound异常(以及其他)开始被抛出。
在网络应用中,您可以执行以下操作:
/// <summary>
/// Due to issues on IIS7, the NHibernate initialization cannot reside in Init() but
/// must only be called once. Consequently, we invoke a thread-safe singleton class to
/// ensure it's only initialized once.
/// </summary>
protected void Application_BeginRequest(object sender, EventArgs e)
{
NHibernateInitializer.Instance().InitializeNHibernateOnce(
() => InitializeNHibernateSession());
}
/// <summary>
/// If you need to communicate to multiple databases, you'd add a line to this method to
/// initialize the other database as well.
/// </summary>
private void InitializeNHibernateSession()
{
var path = ConfigurationManager.AppSettings["NHibernateConfig"];
NHibernateSession.Init(
webSessionStorage,
new string[] { Server.MapPath("~/bin/foo.Data.dll") },
new AutoPersistenceModelGenerator().Generate(),
Server.MapPath("~/App_Configuration/" + path ));
}
// sample of my console app... very simple
static void Main(string[] args)
{
InitializeNHibernateSession();
while(true)
{
Task.Factory.StartNew(() => SomeAwesomeLongRunningPieceOfWork());
}
}
本质上在global.asax中每个线程(Web请求)执行一次初始化。
有关如何在控制台应用中设置此功能(会话管理)的任何想法?
答案 0 :(得分:7)
这对我有用:
// Three threads:
for (int i = 0; i < 3; i++)
{
Thread curThread = new Thread(StartThread);
curThread.Start();
}
private void StartThread()
{
NHibernateInitializer.Instance().InitializeNHibernateOnce(InitializeNHibernateSession);
SomeAwesomeLongRunningPieceOfWork();
}
private void InitializeNHibernateSession()
{
var path = ConfigurationManager.AppSettings["NHibernateConfig"];
NHibernateSession.Init(
new ThreadSessionStorage(),
new string[] { "foo.Data.dll" },
new AutoPersistenceModelGenerator().Generate(),
"./App_Configuration/" + path);
}
关键是这门课,我来自:
http://groups.google.com/group/sharp-architecture/browse_thread/thread/ce3d9c34bc2da629?fwc=1 http://groups.google.com/group/sharp-architecture/browse_thread/thread/51794671c91bc5e9/386efc30d4c0bf16#386efc30d4c0bf16
public class ThreadSessionStorage : ISessionStorage
{
[ThreadStatic]
private static ISession _session;
public ISession Session
{
get
{
return _session;
}
set
{
_session = value;
}
}
public ISession GetSessionForKey(string factoryKey)
{
return Session;
}
public void SetSessionForKey(string factoryKey, ISession session)
{
Session = session;
}
public IEnumerable<ISession> GetAllSessions()
{
return new List<ISession>() { Session };
}
}
它运作得很好。