Generic Specialization

time to read 2 min | 261 words

In C++, it's is common to use template specialization to do all sort of things, from implementing a full blown programs using the compiler as a run time environment to optimizing specific scenario.

For quite some time I have been using a similar methodology in C# 2.0, using a combination of Inversion of Control and generic repository interface to get some really nice results. Here is a simplified diagram of what I'm talking about.

 

 

The generic repository is used to access all the entities in the application. As you can see, I'm starting a unit of work, and then I can get a repository from it. The logic inside the GetRepository<T>() method is a bit involved, but in general, what happens is that the appropriate repository is returned, wrapped in the correct decorators. In the diagram, you can see NHibernate repository and an Active Directory Employees repository, as well as a security decorator.

In practice, I have additional specialized repositories, and several more decorators (transactional, logging, etc). The really nice thing about the whole thing is that most of my entities are handled by NHibernate, which means that I wrote the main thing once, and I can share the implementation between entities. For the special case, I only need to create an implementation of the repository for a specific type and let the UnitOfWork know about it.