A Repository in C# mediates between the domain and data mapping layers (like Entity Framework). It allows you to pull a record or number of records out of datasets, and then have those records to work on acting like an in-memory domain object collection, and you can also update or delete records within those data set, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.
Repository pattern C# is a way to implement data access by encapsulating the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer.
Repository pattern C# also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
Repository pattern C# is mostly used where we need to modify the data before passing to the next stage.
here’s an awesome graph that illustrates the idea:
Why Repository Pattern C# ?
Increase testability: Repository systems are good for testing. One reason being that you can use Dependency Injection. Basically, you create an interface for your repository, and you reference the interface for it when you are making the object. Then you can later make a fake object (using moq for instance) which implements that interface. Using something like StructureMap you can then bind the proper type to that interface. Boom you’ve just taken a dependence out of the equation and replaced it with something testable.
Easily swapped out with various data stores without changing the API: For example, in one instance, you may need to retrieve data from the database, in other cases you may need to retrieve something from a third-party API, or perhaps there’s some other place from which you need to retrieve data. Regardless, the idea behind the repository pattern is that whatever sits behind it doesn’t matter so long as the API it provides works for the layer of the application calling into it.
Entity Framework Repository Pattern C#
Entity Framework (EF) itself implements Unit of work pattern and somewhat loosely implements Repository pattern. With EF you can retrieve a set of records from the database in POCO models. Also, EF keeps track of changes for you within these models and save these changes on single SaveChanges method call.
Let’s see how to create a repository using EF, let say you have customer entity in your application, then this is how your customer repository interface will look like:
The above generic repository defines core operations. You can extend this class and interface base on business requirement and can inherit in your custom repository.
Unit Of Work Pattern C#
Use of separate repository for a single transaction could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.
Unit of work pattern is easy to implement with the use of a generic repository. Let’s see an example,
Unit of Work is the concept related to the effective implementation of the repository pattern, whether its non-generic repository pattern or generic repository pattern.
Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on. You can learn more about Unit of Work from this awesome post.
Repository Pattern C# MVC
Let’s see now how our controller code will look like after using repository pattern along with unit of work:
In the above code we directly initialized unitOfWork variable. Like this,
1 privateUnitOfWorkunitOfWork=newUnitOfWork();
However to truly use the power of repository pattern and make the above controller testable we need to use IUnitOfWork instead of UnitOfWork for our unitOfWork variable data type, and also we have to initialize it using Dependency Injection (DI) technique.
Assuming you’re starting with a new ASP.NET MVC 5 application, the easiest way to get StructureMap is using Nuget package StructureMap.MVC5.
After installing StructureMap, from solution explorer we can notice that Dependency Resolution folder has been added, also StructuremapMVC.cs file in App_Start folder.
The important file which is needed is the DefaultRegistry.cs. In Default Registry class, we are going configure StructureMap container. Let’s see how:
1 publicclassDefaultRegistry:Registry 2 { 3 #region Constructors and Destructors 4 5 publicDefaultRegistry() 6 { 7 Scan( 8 scan=>{ 9 scan.TheCallingAssembly();10 scan.WithDefaultConventions();11 12 //This line of code is just directions telling StructureMap 13 //where to look for DAL models. 14 //Typically, my DAL code lives in different class library15 scan.AssemblyContainingType<ApplicationDbContext>();16 17 //To connect implementations to our open generic type of IRepository, 18 //we use the ConnectImplementationsToTypesClosing method. 19 scan.ConnectImplementationsToTypesClosing(typeof(IRepository<>));20 });21 //For<IExample>().Use<Example>();22 23 //Here we resolve object instances of our DbContext and IRepository24 For<DbContext>().Use(ctx=>newApplicationDbContext());25 For(typeof(IRepository<>)).Use(typeof(BaseRepository<>));26 }27 28 #endregion29 }
After configuring DefaultRegistry replace your CustomerController unitOfWork initialization code with the below code:
I am a software developer, working with MS .NET Platform, I have expertise in coding, reviewing
program functionality, establishing system improvements and testing for security precautions.
Equally adept at developing web applications with visual studio integrated environment.
0 Comments