aha! Thanks, I realize now the issue was to do with a hack that I'd coded in
a while ago to try and fix this:
http://stackoverflow.com/questions/3941359/nhibernate-affecting-non-nhibernate-queries
My issue was that while I am in the process of creating my entity, I call an
external DLL which accesses some of the same databases that my current app
uses. This DLL call was failing, so I committed the transaction before
calling it, and reopened it afterwards. I knew at the time it wasn't the
best way of doing it, but it worked and I couldn't find another way around
it. I think in my recent refactoring I must have moved where that code was
called so now it was causing issues with the transaction.
I've now changed it so that it calls a Flush before accessing this external
DLL, which works fine, but I'm sure that's still not the right way of doing
things. I'm using a session per request model. Here is my session management
class, I'm open to suggestions on how to improve it as I'm fairly new to
NHibernate so I'm still working this all out.
For information, here is my SessionFunctions file:
using System.Runtime.Remoting.Messaging;
using System.Web;
using NHibernate;
namespace BornhorstWard.NHibernate
{
/// <summary>
/// Handles NHibernate
/// </summary>
public abstract class SessionFunctions
{
private const string SESSION_KEY = "current.session";
private const string TRANSACTION_KEY = "current.transaction";
/// <summary>
/// Session factory static and lives for life of application
/// </summary>
public static ISessionFactory SessionFactory = null;
/// <summary>
/// Gest the current session from the HttpContext
/// Unfortunate coupling between this and System.Web, but rather it
here than in UI project.
/// </summary>
public ISession CurrentSession
{
get
{
if (IsInWebContext())
{
return (ISession)HttpContext.Current.Items[SESSION_KEY];
}
else
{
return (ISession)CallContext.GetData(SESSION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[SESSION_KEY] = value;
}
else
{
CallContext.SetData(SESSION_KEY, value);
}
}
}
public ITransaction ContextTransaction
{
get
{
if (IsInWebContext())
{
return
(ITransaction)HttpContext.Current.Items[TRANSACTION_KEY];
}
else
{
return
(ITransaction)CallContext.GetData(TRANSACTION_KEY);
}
}
set
{
if (IsInWebContext())
{
HttpContext.Current.Items[TRANSACTION_KEY] = value;
}
else
{
CallContext.SetData(TRANSACTION_KEY, value);
}
}
}
/// <summary>
/// Checks if its in a web context
/// </summary>
private bool IsInWebContext()
{
return HttpContext.Current != null;
}
/// <summary>
/// Opens a session
/// </summary>
public ISession OpenSession()
{
CurrentSession = SessionFactory.OpenSession();
return CurrentSession;
}
/// <summary>
/// Close a session
/// </summary>
public void CloseSession()
{
if (CurrentSession != null && CurrentSession.IsOpen)
{
CurrentSession.Close();
}
if (CurrentSession != null)
CurrentSession.Dispose();
}
internal void FlushSession()
{
if (CurrentSession != null && CurrentSession.IsOpen)
{
CurrentSession.Flush();
}
}
}
}
Here is a class called NHibernateREquest which is called from my
httpmodule:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
namespace BornhorstWard.NHibernate
{
/// <summary>
/// Starts a session and a transaction with STart
/// and commits trans and closes session with Commit
/// </summary>
public class NHibernateRequest : INHibernateRequest
{
private SessionFunctions _sessionFunctions;
public NHibernateRequest(SessionFunctions sessionFunctions)
{
_sessionFunctions = sessionFunctions;
}
/// <summary>
/// Starts a session and transaction
/// </summary>
public void Start()
{
_sessionFunctions.OpenSession();
ITransaction transaction = _sessionFunctions.ContextTransaction;
if (transaction == null)
{
transaction =
_sessionFunctions.CurrentSession.BeginTransaction();
_sessionFunctions.ContextTransaction = transaction;
}
}
/// <summary>
/// Closes a session and transaction
/// </summary>
public void Commit()
{
try
{
ITransaction transaction =
_sessionFunctions.ContextTransaction;
try
{
if (transaction != null && !transaction.WasCommitted &&
!transaction.WasRolledBack)
{
transaction.Commit();
_sessionFunctions.ContextTransaction = null;
}
}
catch (HibernateException)
{
transaction.Rollback();
throw;
}
}
finally
{
if (_sessionFunctions.CurrentSession.IsOpen)
{
_sessionFunctions.FlushSession();
_sessionFunctions.CloseSession();
}
}
}
}
}
Here is my httpModule:
using System;
using System.Diagnostics;
using System.Web;
using BornhorstWard.NHibernate;
using PmqccDomain.DataAccess.NHibernate;
namespace PMQCC_Website.App_Code
{
public class NHibernateSessionModule: IHttpModule
{
private INHibernateRequest _nhibRequest;
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginTransaction);
context.EndRequest += new EventHandler(CommitAndCloseSession);
Debug.WriteLine("Init Nhibernate module");
}
/// <summary>
/// Opens a session within a transaction at the beginning of the
HTTP request.
/// This doesn't actually open a connection to the database until
needed.
/// </summary>
private void BeginTransaction(object sender, EventArgs e)
{
_nhibRequest = new
NHibernateRequest(NHibernateSessionManager.Instance);
_nhibRequest.Start();
Debug.WriteLine("Starting Transaction");
}
/// <summary>
/// Commits and closes
/// </summary>
private void CommitAndCloseSession(object sender, EventArgs e)
{
_nhibRequest.Commit();
Debug.WriteLine("Committed Transaction");
}
public void Dispose() { }
}
}
The module, and the following class are in the actual project DLL, the other
two are in a separate NHibernate only DLL.
In the project, I have NHibernateSesssionManager which inherits from
SessionFunctions. It's a 'thread-safe, lazy singleton' this class does the
actual nhibernate mappings and configuration fluently.
using BornhorstWard.Infobase.DataAccess.FluentMaps;
using BornhorstWard.NHibernate;
using BornhorstWard.NHibernate.Conventions;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Caches.SysCache;
using PmqccDomain.DataAccess.NHibernate.Maps;
namespace PmqccDomain.DataAccess.NHibernate
{
/// <summary>
/// Configures NHIbernate
/// </summary>
public class NHibernateSessionManager : SessionFunctions
{
private ISessionFactory CreateSessionFactory()
{
log4net.Config.XmlConfigurator.Configure();
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ShowSql()
.ConnectionString(c =>
c.FromAppSetting("connectionString"))
.AdoNetBatchSize(10)
.UseOuterJoin()
.QuerySubstitutions("true 1, false 0, yes
1, no 0")
)
.Cache(c => c.UseQueryCache()
.ProviderClass<SysCacheProvider>())
.ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory,
NHibernate.ByteCode.Castle")
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<ProjectMap>())
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<PmqccFormMap>())
.Mappings(m =>
m.FluentMappings.Conventions.AddFromAssemblyOf<EnumConvention>())
.BuildSessionFactory();
}
#region Thread-safe, lazy Singleton
/// <summary>
/// This is a thread-safe, lazy singleton. See
http://www.yoda.arachsys.com/csharp/singleton.html
/// for more details about its implementation.
/// </summary>
public static NHibernateSessionManager Instance
{
get
{
return Nested.NHibernateSessionManager;
}
}
/// <summary>
/// Initializes the NHibernate session factory upon instantiation.
/// </summary>
protected NHibernateSessionManager()
{
SessionFactory = CreateSessionFactory();
}
/// <summary>
/// Assists with ensuring thread-safe, lazy singleton
/// </summary>
private class Nested
{
static Nested() { }
internal static readonly NHibernateSessionManager
NHibernateSessionManager =
new NHibernateSessionManager();
}
#endregion
}
}
--
You received this message because you are subscribed to the Google Groups
"nhusers" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/nhusers/-/7rhzmRMTtU0J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/nhusers?hl=en.