Non static code design

NHibernate interceptor magic tricks, the example

Below, you can find the final example of working interceptor, which uses some methods described in text of the last few blog entries (1, 2, 3, 4 and 5). Scan the example and go below to get some explanation about it!

The constructor
As you’ve noticed, there is a dependency injection in here! Two arguments are: unity container instance; interface finder, which allows you to use interfaces with their implementation hierarchies. About the second, you can read here and here.

Post flush
does nothing more than ensuring that you’re running it in a transaction. Yep, one for all, all for one!

SetSession
remembers the session instance in a field.

GetEntityName
implementation indicates that there are some interfaces mapped, for instance IA and IB : IA. It allows the most nested interface to be easily find for the object type.

OnPrepareStatement
preserves a sane number of statements per session (hence, per request, because session per request scenario is considered).

Instantiate
is the final method. It uses the passed container to create an instance of the passed class. Having interfaces mapped, it’s must have since you cannot call new for interface :P

Unity registration
Having this interceptor we need a nice and easy way of registering any interceptor (which type is hold in _interceptorType field) in the container. That’s performed by the following unity extension: