我有一个安装了Nihbernate的asp.net应用程序,现在我想把它转换成Windows form应用程序。
以下是在Global.asax.cs中设置的代码。谁能给我一些如何在Windows窗体中做到这一点的代码示例?
protected void Application_BeginRequest(object sender, EventArgs e)
{
ManagedWebSessionContext.Bind(HttpContext.Current, SessionManager.SessionFactory.OpenSession());
}
protected void Application_EndRequest(object sender, EventArgs e)
{
ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory);
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
{
session.Transaction.Rollback();
}
else
{
session.Flush();
}
}
finally
{
session.Close();
}
}
}发布于 2010-02-28 13:23:53
在statefull应用程序中访问ISessionFactory有几种方法(桌面应用程序就是这样的应用程序),其中包括:
单例您可以在程序启动时构建一次会话工厂,然后通过静态单例类访问它。这将强制应用程序仅使用会话工厂的一个实例。
示例:
public sealed class NHibernateHelper
{
private static ISessionFactory SessionFactory;
private static readonly Configuration NhibernateConfig;
// ....
static NHibernateHelper()
{
NhibernateConfig = new Configuration().Configure();
SessionFactory = NhibernateConfig.BuildSessionFactory();
}
public static ISessionFactory GetSessionFactory()
{
return SessionFactory;
}
// ....
}..。并在整个应用程序中通过GetSessionFactory方法访问会话工厂。
上下文对象和/或依赖项注入
您可以通过配置构建会话工厂,并将其传递给整个应用程序的上下文对象。
示例:
启动过程中的
//在这里配置NHibernate。ISessionFactory _sessionFactory = BuildMySessionFactory();// ...ObjectFactory.Initialize(x => { x.For() .Use() .Ctor().Is(_sessionFactory);// ...初始化剩余的存储库...});然后
公共类StandardPatientRepository : IPatientRepository {私有只读ISessionFactory _sessionFactory;公共会话(ISessionFactory sessionFactory) { if (sessionFactory == null)抛出新会话(“sessionFactory”);_sessionFactory = sessionFactory;}公共虚拟患者Get(Guid ){ using (IStatelessSession session = _sessionFactory.OpenStatelessSession()) { return session.Get( id);}} //其余的数据访问方法。}
然后在你的类中使用数据(即。使用存储库),您将使用:
Patient = ObjectFactory.GetInstance<IPatientRepository>().Get(patient);在我看来,第二种方法更好,因为我认为单例在大多数情况下是一种反模式。第二种方法将使您能够更好地控制您的数据层,您将知道谁在何时访问它。
发布于 2010-02-28 17:55:13
下面是一个在桌面应用程序中使用NHibernate的出色且广泛的示例应用程序:
Building a Desktop To-Do Application with NHibernate
在桌面应用程序中管理NHibernate会话往往比在web应用程序中管理NHibernate会话复杂得多。
https://stackoverflow.com/questions/2350083
复制相似问题