Sharing Contexts and Repositories

Class libraries are meant to be shared. It can be used by web applications. It can be used by services. It can be used by batch programs. With that in mind, it is important to think about contexts and repositories as class libraries, that are meant to be re-used and shared by your current application project and by your future application projects.

Most ASP.Net MVC samples would show creating the context and repositories within the application project. They work, yes, but they can also be misleading. Note that you can create your DbContext instance in its own class library project and just reference it in your application. Likewise, if you are creating repositories, note that they can also be class library projects themselves that can be referenced by your application.

The separation of contexts and repositories in to their own class libraries is crucial when you want to re-use them and share as-is with applications other than your current application project. It may not be what's required now, but it may become a requirement in the future. These "other" applications can be batch programs for example, or web services, or WebAPI projects, or what have you.

Planning your assets for the future is as important as architecting the details of your solution. By considering the possibilities that an asset can become useful elsewhere, designing and developing them as potentially sharable assets from day 1 can be a smart move.

Mendz.Data and its family of Mendz.Data.* packages are designed with that in mind. Use Mendz.Data to create your context and repository class libraries that can survive future needs and requirements.

Comments