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.