Mid From PDF SOLID Design Patterns & SOLID

How do you configure EF Core Repository and Unit of Work in .NET Core?

  • Register DbContext with DI in Startup.cs:

services.AddDbContext<AppDbContext>(options =>

options.UseSqlServer(Configuration.GetConnectionString("DefaultConne

ction")));

  • Implement Repositories for entities injecting AppDbContext.
  • Implement Unit of Work which holds multiple repositories and calls SaveChanges()

on the DbContext:

public interface IUnitOfWork : IDisposable
{

IProductRepository Products { get; }

int Complete();
}
public class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext _context;
public IProductRepository Products { get; private set; }
public UnitOfWork(AppDbContext context)
{
_context = context;
Products = new ProductRepository(_context);
}
public int Complete() => _context.SaveChanges();
public void Dispose() => _context.Dispose();
}

Register UnitOfWork in DI container as Scoped.

More from Design Patterns in C#

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details