Dynamic Repository Pattern

We probably only want to access a single data source from our application, but we also want it to be easy to swap this out so we can support multiple clients. We can achieve that using dynamic repository interface.

By using dynamic repository interface, we will be able to remove references to any specific repository in our calling code. This means that if we need to add a new repository, we do not need to recompile our entire application. This may not be big a problem for an internal application. But if we ship our application out to multiple clients, then each client could potentially have a different build, and that is a support nightmare.

How to implement this ?

The first thing we’ll need to do is get some information out of our configuration file.


The value for in the App.config is an assembly qualified name for a specific type that we want. The assembly qualified name consists of four parts. The first part is the fully qualified type EmployeeRepository.Service.ServiceRepository. The second item is the assembly name, EmployeeRepository.Service, and that references the EmployeeRepository.Service.dll file. We can find a DLL on the file system and load a type from it.

After we get the RepositoryType name, we need to create a Type object. ‘as IEmployeeRepository’ will try to do a cast to the appropriate type. If it’s not successful, it will return null rather than throwing an exception.

Factory Method

The load data function in the viewer just returns the object as supplied by the factory method. Then it calls the GetEmployees() of that implementation to return collection of Employees.

Load Data function in the Viewer

This means that if we need to switch from service call to SQL Repository, and we do not need to recompile the code. Our calling code will get data from the repository type we are targeting in the config.

Creating a generic factory method moves the details out of our main application so that we could focus on the important functionality, getting a collection of Employee objects that we can display for our users.

As much as I love this design pattern, there are drawbacks to this approach. Debugging is much more complicated, so we only want to use this where we will get the benefits like in a multi-client scenario.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store