如何在多线程控制台应用程序中使用Sharp架构设置NHibernate
本文关键字:Sharp NHibernate 设置 多线程 控制台 应用程序 | 更新日期: 2023-09-27 18:06:38
我对这些技术还很陌生。这里真正的问题是如何管理控制台应用程序中每个线程的会话。目前,如果我将其作为单个线程运行,那么一切都很好。一旦我切换到多线程模型,我将开始在会话级别看到争用(因为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中每个线程(web请求)执行一次初始化。
关于如何在控制台应用程序中设置此(会话管理)的任何想法?
这对我有用:
// 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=1386年http://groups.google.com/group/sharp-architecture/browse_thread/thread/51794671c91bc5e9/386efc30d4c0bf16 efc30d4c0bf16
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 };
}
}
效果很好