DEV Community

Cover image for Clean Architecture: Why I Stopped Injecting DbContext Directly
Javid KoluRazhan
Javid KoluRazhan

Posted on

Clean Architecture: Why I Stopped Injecting DbContext Directly

In my early days with ASP.NET Core, I often injected DbContext directly into controllers or services. It worked — but over time, things got messy: hard-to-test code, tight coupling, and business logic leaking into the infrastructure.

Here’s what I do now:
I use the Repository Pattern + Unit of Work to abstract away the data access logic. My services talk to interfaces like IOrderRepository, not DbContext.

Image description

public interface IOrderRepository
{
    Task<Order> GetByIdAsync(Guid id);
    void Add(Order order);
}
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Easier unit testing (mocking repositories)

  • Clear separation of concerns

  • Domain logic is not mixed with EF-specific code

Tip:
If you're working on a medium-to-large project, try isolating EF Core behind interfaces. It’s a small change that pays off big time.

Top comments (0)