问题描述
|
我正在尝试将Fluent NHibernate与ASP.NET MVC 3一起使用,但似乎找不到教程来说明如何使用ASP.NET MVC进行配置。我主要想知道将ISession构建函数放在哪里以及在需要时如何调用它。我看到了许多不同的实现,但是没有一个实现指定将代码放置在何处。因此,如果任何人都可以解释如何将其全部配置为与MVC 3一起使用,或者在哪里有非常详细的教程,将不胜感激。
解决方法
您可以看看S#arp体系结构。
这是一个非常坚固的体系结构框架,可与ASP.NET MVC和NHibernate一起使用。他们有一个不错的文档,并且有一些示例项目需要研究。
http://www.sharparchitecture.net/
, 如果您没有使用依赖注入,则可以尝试这样的操作
public class MvcApplication : System.Web.HttpApplication
{
public static ISession CurrentSession
{
get { return (ISession)HttpContext.Current.Items[\"current.session\"]; }
set { HttpContext.Current.Items[\"current.session\"] = value; }
}
private static ISessionFactory _session_factory;
private static object _session_factory_lock = new object();
protected static ISessionFactory CreateSessionFactory()
{
if (_session_factory != null) return _session_factory;
if (ConfigurationManager.ConnectionStrings[\"DbConnection\"] != null)
{
var conn = ConfigurationManager.ConnectionStrings[\"DbConnection\"];
SqlServerSessionFactoryBuilder fb = new SqlServerSessionFactoryBuilder(conn.ConnectionString);
_session_factory = fb.GetSessionFactory();
return _session_factory;
}
throw new Exception(\"Cannot build session factory,connection string is not defined.\");
}
public MvcApplication()
{
_session_factory = CreateSessionFactory();
BeginRequest += delegate
{
try
{
CurrentSession = _session_factory.OpenSession();
}
catch (FluentConfigurationException ex)
{
logger.FatalException(string.Format(\"Error configuring the database {0}\",ex.Message),ex);
}
};
EndRequest += delegate
{
if (CurrentSession != null)
{
if (CurrentSession.Transaction != null && CurrentSession.Transaction.IsActive)
{
logger.Error(\"Rolling back uncommited transaction\");
CurrentSession.Transaction.Rollback();
}
else
{
CurrentSession.Flush();
}
CurrentSession.Close();
}
};
Error += delegate
{
var error = this.Server.GetLastError();
logger.ErrorException(string.Format(\"Unhandled error : {0}\",error.Message),error);
};
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}