views:

281

answers:

2

The application i am currently working on makes heavy use of the repository pattern with NHibernate. We have a generic base repository class that implements standard gets and saves. This class is then inherited by repositories for each type. These repositories can then add their own type specific methods (and override saves and gets if neccesary).

This works well and from a seperation of concerns point of view means that our business objects are POCO's and our repository classes handle the specifics of saving. practically however it would be very useful when we have a type to be able to say "Get me the repository that can save this type". What patterns are there that can be used to do this? Do I need to maintain my own lookup table? can a lookup table be maintained automatically somehow?

A: 

Using reflection and some naming convention for example:

DomainObjectNameRepository

You could dynamically instantiate the repository you are looking for using Activator.CreateInstance. Aslong as you know how they are named using the example as an example above. Other wise you also have the registry pattern. Create a mapping element inside the web.config file for instance and then you could have a method in the Registry called ResolveRepository.

Registry.ResolveRepositoryFor<T>() where T:DomainObject;

Another bonus to this is that you could use IOC with it, inversion of control with example Unity.

The mapping file would map DOmainObject to Repository and then inside the registry method, it could then use Unity to resolve the instance of that specific Repository, for example and have them as singleton instances.

Andrew

REA_ANDREW
+5  A: 

Looks like your ready for a Dependency Injection Framework

David Kemp