© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
18 replies
Aokiri 🐸

Confusion about Repository Pattern and Unit of Work.

Hi there. I recently applied the Repository Pattern and Unit of Work in an API I'm creating, and everything was going well. However, I got stuck trying to understand how to pass the Database Context to the implementation of one of my interfaces. I'm trying to grasp it, but I can't figure it out. I'll attach few code for reference:

(Program.cs) Here is where I'll apply Dependency Injection for my ICategoryRepository with a Scoped lifetime:
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();

(DataAccess/Repository/Repository.cs) Here is my implementation of my Repository Interface (only constructor and fields):
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly ApplicationDbContext _db;
        internal DbSet<T> dbSet;

        public Repository(ApplicationDbContext db)
        {
            _db = db;
            this.dbSet = _db.Set<T>();
            // For example, _db.Categories == dbSet
        }
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly ApplicationDbContext _db;
        internal DbSet<T> dbSet;

        public Repository(ApplicationDbContext db)
        {
            _db = db;
            this.dbSet = _db.Set<T>();
            // For example, _db.Categories == dbSet
        }


(DataAccess/Repository/CategoryRepository.cs) And here is my implementation of my Category Repository Interface (only constructor, as always):
    public class CategoryRepository : Repository<Category>, ICategoryRepository
    {
        private readonly ApplicationDbContext _db;

        public CategoryRepository(ApplicationDbContext db) : base(db)
        {
            _db = db;
        }
    public class CategoryRepository : Repository<Category>, ICategoryRepository
    {
        private readonly ApplicationDbContext _db;

        public CategoryRepository(ApplicationDbContext db) : base(db)
        {
            _db = db;
        }


Look how these two has inyected with the DbContext, but here comes my confusion...

In the controller, I created an ICategoryRepository object, but I don't understand how it pass the DbContext to the controller itself...
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ CQRS and Repository pattern
C#CC# / help
4mo ago
❔ Repository pattern
C#CC# / help
3y ago
❔ How can I better understand the concepts of unit of work and repository pattern in C# .NET 7?
C#CC# / help
3y ago
Repository Pattern and Clean Architecture
C#CC# / help
11mo ago