我对这些技术还是很陌生。这里真正的问题是如何在控制台应用程序中管理每个线程的会话。目前,如果我将它作为单个线程运行,那么一切都很好。一旦我切换到多线程模型,我就会开始看到会话级别的争用(因为 Session 对象在设计上不是安全的) KeyNotFound 异常(以及其他)开始被抛出。
在 Web 应用程序中,您会执行以下操作:
/// <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 中每个线程(网络请求)执行一次初始化。
关于如何在控制台应用程序中设置此(会话管理)的任何想法?