Contextual data using NHibernate filters

I'm in the middle of the development process of an application using NH for data access, and I'm faced with a requirement that could be stated as follows:

The application needs to provide support for different Contexts of execution, and certain entities must be context-aware, which means that at a given time, the application only see instances of those entities that corresponds to the current context of execution.

Now, just remember that I have several entities defined that are used throught the entire application layer stack, so I wanted to solve this issue modifying as little as possible.

I'm very proud with the solution that I came up with, and also very amazed by the power of NHibernate.

To simplify a little lets assume that I have a static class that defines the current context of execution:

Just do this (cfg is the NH Configuration object) before building the session factory and it creates the correct filter definition and adds the condition to every entity mapped that implements IContextAware.

At this point we just have our filter defined; now we need to enable it in order to actually filter something. It would be very handy if we can enable filtering at session factory scope, but since the session factory is immutable we need to enable it for each session that we will be using.

Wait.... maybe something else can do this work for us...

The following interceptor actually takes care of 2 things:

enables the context filter as soon as it is attached to the session, and

assigns the correct value to the Context property of entities implementing IContextAware when they are persisted.