views:

38

answers:

1

Can I do this?
I have the following in my code:

public class ARClass : ActiveRecordBase<ARClass>
{
      ---SNIP---

    public void DoStuff()
    {
        using (new SessionScope())
        {
            holder.CreateSession(typeof(ARClass)).Lock(this, LockMode.None);
            ...Do some work...
        }
    }
}

So, as I'm sure you can guess, I am doing this so that I can access lazy loaded references in the object. It works great, however I am worried about creating an ISession like this and just dropping it. Does it get properly registered with the SessionScope and will the scope properly tare my ISession down when it is disposed of? Or do I need to do more to manage it myself?

A: 

As far as I can tell, yes this works fine. I have found no issues with this method.

I have an abstract base class that all of my AR classes inherit from. In this class, I define a Reattach function. This works fine, as long as you are careful. It will not work if you are outside an active SessionScope or if the object is already attached to an active ISession.

This is what it looks like:

public abstract class BaseModel<T> : ActiveRecordLinqBase<T> 
{ 
    public virtual void Reattach() 
    { 
        if (!holder.ThreadScopeInfo.HasInitializedScope) 
            throw new Exception("Cannot reattach if you are not within a SessionScope."); 
        holder.CreateSession(typeof(T)).Lock(this, NHibernate.LockMode.None); 
    } 
} 
oillio

related questions