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.
public interface IOrderRepository
{
Task<Order> GetByIdAsync(Guid id);
void Add(Order order);
}
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)