Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

72 Comments

  1. Great Article. Quick question, can the repository pattern above be implemented with the CQRS pattern?
    How would that work? Awesome job as always.

    1. It really “depends”. If you are building a small application, NO. If you are a building an Enterprise level application with like 10K Lines of code, you would benefit by deceoupling the dbContext away from the Application layer. The only problem that i see is that you would end up with on additional layer of arbitration. But if you want to keep your code organized and much testable, Repository is the way to go. I have seen a couple of Projects over at GitHub implementing both Repository Pattern and CQRS. It’s used, but not widely.

    2. Hi again, Have a look at https://github.com/dotnet-architecture/eShopOnWeb . This is one of repositories maintained by Microsoft themselves. You can see at https://github.com/dotnet-architecture/eShopOnWeb/blob/master/src/Web/Features/MyOrders/GetMyOrdersHandler.cs that they themselves are using Repository Pattern along with CQRS. Summary is that, if you think it is maintainable and easy to understand for you, then Repository + CQRS is also a way to go about it.

      Thanks and Regards

  2. Hey , I am just a beginner in .net and c# . And I want to know about the job opportunities in c# .net in India .
    I am in final year of my graduation which is done now and I want to get a job and basically I am from a bit of java background like core Java and few days back a got an internship where i work on Microsoft dynamics 365 technology and where i have to work on JavaScript and C sharp . So please tell me what I do further

  3. Please read this article:

    https://altkomsoftware.pl/en/blog/create-better-code-using-domain-driven-design/

    “In domain driven design a repository is not just a data access object, which implements all CRUD and database queries needed for given entity type. In domain driven design repository should be part of the ubiquitous language and should reflect business concepts. This means that methods on repository should follow our domain language not the database concepts.
    We often see generic repositories with methods for CRUD and methods allowing execution of ad-hoc queries. This is not a good way if we want to follow DDD principles.
    Instead we should only expose operations required and create methods for queries related to business concepts.”

    What you’ve built here is more like a “document database” and your entities more like “mutable documents” than entities.

    Don’t feel bad though. Everyone gets this wrong at first, and all the popular articles on the subject teach it this way. Once you’ve tried repositories the DDD way, you’ll see the benefits. 🙂

    1. I’m new developer and I’ve read a lot about repository and DDD,
      and it seems that DDD is only recommended to large enterprise applications.

      In small and medium applications can still I use instead repository pattern as “document database” ?

      1. Usage of design patterns solely depends on the developer. If you are comfortable and think that Repository pattern makes sense, go ahead with it. This patterns helps make your application more decoupled.

        Thanks and Regards

    2. This is more a matter of scoping, than anything else. The problem is not in using a generic repository, but in allowing that generic repository to be consumed outside of the domain layer. It absolutely makes sense for generic implementations of CRUD – but for those implementations to be scoped to only being accessible in the concrete repository, itself. So, while a Person repository might expose a method to AddPerson() in regards ubiquitous language, there is nothing saying that the Person repository not have a way to internally do basic CRUD Insert() in a fashion detached from that scope.

      So many DDD enthusiasts grab pitchforks and torches whenever generic and repository are uttered in the same sentence, and I used to be one of those people. I fully agree that we want to hide CRUD from the consumers of the repository, but there is value in allowing it within. In the real world, having the time to design, implement, and execute a true DDD framework is a challenge, at best, but there are parts of DDD which should be encouraged in projects of any scale. A well-defined and UL-scoped set of repositories is one of the easier wins and an internally scoped generic repository which only those concrete repositories can use is as valuable as it is attainable to projects of any size.

  4. Thank you for this article.

    I’ve been using repository pattern since MVC4 but haven’t used GenericRepository and UnitOfWork. I just started a new project using .NETCore Api and MongoClient for MongoDb. I will try using this approach and if it works then this will become my new design pattern.

    Thanks Mukesh.

  5. What about using a generic UnitOfWork Pattern. Otherwise, any time you want to add a new repository (e.g. ManagersRepository, TasksRepository) you will have to change your IUnitOFWork interface as well as the concrete UnitOfWork class

  6. How would be the idea of implementing repository patter with onion architecture? Can you please direct me with some articles?

      1. Thanks, Mukesh. I am working on learning new architectures and patterns (I have developed all my projects with only N-layer). I view your blog will be a lead to it. I will go through the repository for better knowledge.

        1. Hi Mukesh, I was going through your GitHub repo on CleanArchitecture. It has served me to acquire knowledge about architecture in detail. I would wish to know if the UOW layer is not required/possible or have you proposed to integrate in the future.

          Thanks in advance

          1. Hi Jugan,
            Yes, since the Repository pattern implementation depends on the develops choice, it can still be clean with a UOW Layer. But to have a much better separation, UOW is a must. I am still in process of building the API. (Currently working on the Auth Services). I will be adding the UOW as well in a few days. However I guess you can get a good overview of clean architecture via the github repo already. Do share it within your community.

            Thanks and Regards.

  7. Great article! Good job on it, I’ve learned quite a lot. I just have a question.
    Is there any particular reason to keep the repositories registered once you implemented the unit of work?

    Can we have
    services.AddTransient();

    Instead of
    services.AddTransient(typeof(IGenericRepository), typeof(GenericRepository));
    services.AddTransient();
    services.AddTransient();

    If not, what is the reason to keep the repositories? Thanks in advance and keep up the great work!

    1. Hey, Thanks for the feedback.

      Yes, Thanks for pointing out that to me. You really don’t need to Register the IRepos and UOW takes care of all that. You will just need a services.AddTransient(); in your startup. That’s all you would need. I guess I have left out some residue code.

      Thanks and Regards

  8. Good article. However, may I suggest a few improvements:
    1. Do not return IEnumerable but instead use IQueryable. With the IEnumerable, you are forcing the queries to load the whole data in the table in memory. This is not only slow but may also crash your server if you have large tables with limited RAM. The IQueryable would allow you to improve the performance.
    2. You do not need the unit of work pattern. EF Core already implements it. See this post (https://www.programmingwithwolfgang.com/repository-pattern-net-core/) for better generic repository implementations.

    Either way, thanks for your detailed explanations.

  9. Hey, nice article only question is how you will implement an identity framework in this pattern I mean in which layer? I have read many articles in which the user manager and sign in manager are used within the controller itself which means giving the database calls from the controller. Any idea or article on this will help thanks.

    1. Hi, I would not put them within the controller. If I was using an Onion Architecture, I would add an IAccountService, that has AuthenticateAsync, RegisterAsync and so on. Then I would create a new Infrastructure Layer, Infrastructure.Identity and implement IAccountService in this layer. I dont have an article regarding the same, but you can check my Clean Architecture in WebApi Repository – https://github.com/iammukeshm/CleanArchitecture.WebApi . The same concept is implemented here.

      Thanks and Regards

  10. Hi! Thanks for the article! It’s very nice!

    Several years ago I was developing with Symfony 2 framework. Doctrine is used as ORM with unit of work and repositories there.

    The thing is, one of the practices there was: create service, which inherits from default entity repository (with all common methods, findById, find, findAll etc). So instead of getting generic repository we were able to get generic repository as service + our additional methods in this service. Basically a win-win situation. We had full first-level access to all the default methods of repositories with our additional methods like “findByEmail” or “findByRelationshipId” etc.

    You can see example of such thing here: https://tomasvotruba.com/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/

    When I started using AspNet with Entity Framework Core, I was surprised that I did not witness word “Repository” anywhere.
    Some time passed and I discovered that actually EF Core introduced unit of work and repositores as db context, and apparently Entity Framework did not have those inside.

    Is it possible in AspNet + Ef Core to code like it is possible in Symfony + Doctrine? To create separate repositories of entities which wll inherit all default DbSet methods etc? Maybe it is the way, to create custom class which would extend DbSet and register it inside DbContext?

  11. Hi, Mukesh sir,

    I understood this . But could you please let me know how to use Unit of Work in Two tables when we need to join table. Furthermore, how to setup generic repository for multiple table query

  12. Hi Mukesh
    Well explained and simply explained. Very good for those who likes to use this pattern without diving deep to the theory of patterns and what each part does, All blogs are super
    Hope we can meet some time in TVM

  13. Hi Mukesh,
    Great article. But what will be the problem if we refactor the GenericRepository as like

    public interface IGenericRepository where T : class
    {
    Task GetByIdAsync (int id);
    Task<IEnumerable> GetAllAsync ();
    Task<IEnumerable> FindAsync (Expression<Func> expression);
    Task AddAsync (T entity);
    Task AddRangeAsync (IEnumerable entities);
    Task RemoveAsync (T entity);
    Task RemoveRangeAsync (IEnumerable entities);
    }

  14. Hello
    It is a wonderful article.
    I have a question “sorry if It seems stupid”
    In the developer controller we have injected IUnitOfWork in the controller’s constructor, so the .Net core framework will take care of providing a UnitOfWork instance to the controller, but UnitOfWork needs ApplicationContext instance to be constructed.
    The question is Who will provide this ApplicationContext instance to the constructor of UnitOfWorkClass?

  15. Hi, Thanks to your article !
    Question : Is the instantiation of repositories in the UnitOfWork class is respectfull of dependency injection principe ?
    If not, how can i fix it ?

  16. Hi .. Thanks Much for the article … If you could please suggest a way to avoid the database concurrency issues using this pattern as db context has to be disposed off immeadiately .. Appreciate it

  17. Hi, nice article!
    One question though, did you forget to add an Update methode ? Seems like all the CRUD’s are there but and update is missing ?

    1. I was thinking the same thing. Will this work:
      public T Update(T entity)
      {
      var entityEntry = _context.Update(entity);
      return entityEntry.Entity;
      }

  18. Line number 7 and 8 of unitofwork. Why you are newing developerrepository since you have the IDeveloperRepository interface?

    1. Hi Zach,
      Did you ever figure this out? I’m trying to do the same–include related lookup-entities. The scaffolded controller in a single project MVC core solution in VS 2022 takes care of it automatically but I’m trying to figure out how/where this would be done with a separate repository. Thanks.

  19. It’s a nice article but I am getting an error while adding migration. Please have a look at the error below. I also selected DataAccess.EFCore from the dropdown. Any help will be highly appreciated.
    Your target project ‘DataAccess.EFCore’ doesn’t match your migrations assembly ‘Domain’. Either change your target project or change your migrations assembly.
    Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly(“DataAccess.EFCore”)). By default, the migrations assembly is the assembly containing the DbContext.
    Change your target project to the migrations project by using the Package Manager Console’s Default project drop-down list, or by executing “dotnet ef” from the directory containing the migrations project

  20. Thank you very much for the great article .
    If you can update this article with implantation AutoMapper I will be very grateful.
    And if you can make example of loading related data will be nice
    Best Regards

  21. Hi Mukesh,
    It’s a great article to understand the repository pattern in a unit of work. Can we use this approach for async operations? I have used the Repository pattern in my project without Unit of Work, and I am getting below exception when I can try to do multiple database operations in the same service.

    A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.

  22. Hello Mukesh,
    Really appreciated!
    you have simplified the complex process into a simple line of code which will help the community to clear the fundamental of code and functionality.

    Thanks for sharing the detailed information

  23. can you explain hoe to testthe Iunit of work implemention for all the CURD operations

  24. This article is clear and concise. I’ve been struggling to understand the repository pattern for some time now, and now I understand it. Keep up the good work!

  25. My project
    WebAssembly…

    I was using simple pattern.
    (client side) blazor page httpclient service ==> (server side) api controller return answer

    I heard that AddScoped, AddTransient, AddSingleton has some reason to use.
    So… I changed to use interface.
    (client side) blazor page call => interface => httpclient service ====> (server side) api controller => interface => dbcontext manager ===> api controller return answer

    It is too hard work to add even one query…..
    And this post… make my brain to be stop…. ㅡ..ㅡ;;
    I made copy of all files in this post.. Anyway and now I will run this solution using generic interface.

    There are too many different kind of Dbcontext in my project. I want to have a simple and combined single interface ^____^;;;

  26. Hi, why typeof?
    services.AddTransient(typeof(IGenericRepository), typeof(GenericRepository));

  27. Hi,

    Good article and examples, but I have a question: The Repositories shouldn’t be injected on the constructor of the UnitOfWork class instead of being instatiated directly?

  28. I have been looking around for a perfect example of a repository pattern. This is close to what I’m looking for. However, is it a correct approach to keep the return type of all of these methods (Add/Remove etc.) inside the repository class to void?

  29. “Make sure that you have set your Startup Project as WebApi and the Default Project as DataAccess.EFCore”

    I knew we can set up “default setup project”, but setting startup and default projects separately is new to me.
    Can you maybe explain this, as I could not find a good search result that highlights the difference between them.

    Thanks for the articles, I am a regular reader now 🙂

  30. Pingback: How to force Entity Framework to always get updated data from the database? - Design Corral
  31. Hi, thanks for a great article.

    In your UnitOfWork example, where you insert a Developer and a Project, I note that you have no IDs in either object.
    In a real-world situation, however, we would need to relate the Developer to their Project. Typically there would be a foreign key in Project pointing toward its Developer:

    public class Developer
    {
    public int DeveloperId {get; set;}
    public string Name {get; set;}
    }

    public class Project
    {
    public int ProjectId {get; set; }
    public int DeveloperId {get;set;}
    public string Name {get; set;}
    }

    So when you add a Project, you need to include its DeveloperId. However, when you insert the Developer, you don’t know what the ID is going to be until you call context.SaveChanges() / context.SaveChangesAsync().

    How do you deal with this situation?

    Thanks!

  32. Also, can you say more about the service layer that ideally would sit between the controller and the repository? I think that may be the answer to my earlier question.

    Thanks!

  33. Understood why we used a Generic Repository instead of a IDevloperRepository?? When there are large number of entites in our application, we would need seperate repositories for each entities. But we do not want to implement all of the above 7 Functions in each and every Repository Class, right? Thus we made a generic repository that holds the most commonly used implementaions.
    These line makes me confusion. can any one explain it with little bit elaborate plz.