Reputation: 3752
Randomly NHibernate seems to fail with an IndexOutOfRange Exception. The code works most of the, time but causes random application crashes.
public T GetByID<T>(Guid Id) where T : Modules.Common.EntityBase
{
try
{
ISession session = NHibernateHelper.GetCurrentSession();
var product = session
.CreateCriteria(typeof(T))
.Add(Restrictions.Eq("Id", Id))
.UniqueResult<T>();
return product;
}
catch (HibernateException ex)
{
NHibernateHelper.CloseSession();
throw;
}
}
I'm using the code on a WCF Service where ISessions are managed for each individual httpcontext, so i don't think it's due to thread safety. The Exception comes from DataReader so I'm going to guess that it is comming from the UniqueResult line.
Here is the get Current Session function
public static ISession GetCurrentSession()
{
if (HttpContext.Current == null)
{
lock (sessionLock)
{
if (_session == null)
_session = sessionFactory.OpenSession();
}
return _session;
}
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
Upvotes: 0
Views: 263
Reputation: 3752
Turns out that in WCF HttpConext is null, which because I based the thread separation on the current HTTPContext (assuming that it functioned like a regular web app).
Saw a tutorial on Getting NHibernate to work with WCF that looked like it may work, but had problems implementing the solution. However it REALLY seems complex to use this method in a per request scenario... there's like 5 object, it requires modifying each of the services.
Point to note that if they are working in only an HTTP environment you can use the AspNetCompatibilityRequirements attribute and config section to get WCF to have HTTPContext values.
Class:
[System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Required)]
public class CaseService : ServiceBase, ICaseService
{
...
}
Web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
...
</system.serviceModel>
I read somewhere that a WCFSessionProvider (or something to that effect) is provided in NHibernate 3.0 so I'll wait for that solution to make the real solution.
Upvotes: 0
Reputation: 5958
maybe a long shot, but check this IndexOutOfRangeException Deep in the bowels of NHibernate
Upvotes: 1