Posted by Anuraj on Tuesday, February 14, 2017
This post is about implementing the Repository and Unit of Work Patterns in ASP.NET Core. The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD). Long back I wrote a post on implementing a generic repository in ASP.NET 5 (Yes in ASP.NET 5 days, which can be used in ASP.NET Core as well.). So I am not explaining more on Repository pattern. The UnitOfWork pattern is a design for grouping a set of tasks into a single group of transactional work. The UnitOfWork pattern is the solution to sharing the Entity Framework data context across multiple managers and repositories.
As mentioned, Unit Of Work pattern helps developers work with multiple repositories share single database context. This way, when a unit of work is complete, you can call the savechanges method of dbcontext, which will make sure all the changes associated with the context is saved to the database. I am using ASP.NET Core dependency injection feature to inject dependency to the controllers.
Here is my unit of work implementation. It has all the repositories as properties and a common save method.
Note: Unit of work pattern voilates the Open Closed Priciple, each repository / model (if you are using generic repository), you need to add to unit of work class as property.
And here is the implementation.
Here is my `ConfigureServices method.
And you can use the unit of work like this.
_unitOfWork is injected to the controller constructor via ASP.NET Core dependency injection.
Here is the screenshot of the query getting executed.
Happy Programming :)