c a n d l a n d . n e t

Making Sure A NHibernate IInterceptor Is In The Session

Dusty Candland | |

Building on the previous post Intercepting NHibernate to Handle Additional Database Work, I used the ILifecycle interface to ensure the IInterceptor was setup on the session before saving MyEntity. I ILifecycle interface is deprecated, but I needed some way to make sure the interceptor was there. If an entity has the ILifecycle interface nothing more is needed, NHibernate will call the methods. I used the OnSave method, to inspect the session instance and throw and exception if needed. Anyway, here’s the code:

public class MyEntity : ILifecycle
{
    public virtual int Id { get; set; }
    public virtual int ParentId { get; set; }

    public virtual LifecycleVeto OnSave(ISession s)
    {
        var sessionDelegate = s as SessionDelegate;
        var session = sessionDelegate != null ? sessionDelegate.InnerSession as SessionImpl : s as SessionImpl;

        if (session != null && session.Interceptor.GetType().Equals(typeof(MyEntityInterceptor)))
            return LifecycleVeto.NoVeto;

        throw new ApplicationException("MyEntityInterceptor needs to be registered with the container.");
    }

    public virtual LifecycleVeto OnUpdate(ISession s)
    {
        return LifecycleVeto.NoVeto;
    }

    public virtual LifecycleVeto OnDelete(ISession s)
    {
        return LifecycleVeto.NoVeto;
    }

    public virtual void OnLoad(ISession s, object id)
    {
    }
}

I think there are potentially better ways to handle this, but with the existing constraints on the code and time work something out, this was the way I went.

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: