Multiple generic repositories in unitofwork?

后端 未结 3 1339
南笙
南笙 2021-01-07 05:38

Lets say I have 2 tables. ProductCategory and Product. I have 1 generic repository that can handle both tables:

public class Generi         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-07 06:08

    You can add a generic method to the IUnitOfWork interface:

    public interface IUnitOfWork : IDisposable
    {
        int SaveChanges();
    
        IRepository Repository();
    }
    

    But i don't recommend it. It's smells like Service Locator anti-pattern and SRP violation. Better way is to remove all repositories from the IUnitOfWork interface, because providing access to repository is not UnitOfWork's responsibility. I recommend to separate repository from UnitOfWork and inject their into the consumer by itself.

    public class Consumer
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRepository _products;
    
        public Consumer(IUnitOfWork unitOfWork, IRepository products)
        {
            _unitOfWork = unitOfWork;
            _products = products;
        }
    
        public void Action()
        {
            var product = _products.GetOne();
    
            product.Name = "new name";
            _products.Update(product);
    
            _unitOfWork.SaveChanges();
        }
    }
    

    UDATE:

    UnitOfWork and Repository can share context instance. Here the sample of code:

    public class EfUnitOfWork : IUnitOfWork
    {
        private readonly DbContext _context;
    
        public EfUnitOfWork(DbContext context)
        {
            _context = context;
        }
    
        public void SaveChanges()
        {
            _context.SaveChanges();
        }
    }
    
    public class EfRepository : IRepository where T : class
    {
        private readonly DbContext _context;
    
        public EfRepository(DbContext context)
        {
            _context = context;
        }
    
        //... repository methods...
    }
    
    public class Program
    {
        public static void Main()
        {
            //poor man's dependency injection
            var connectionString = "northwind";
    
            var context = new DbContext(connectionString);
            var unitOfWork = new EfUnitOfWork(context);
            var repository = new EfRepository(context);
            var consumer = new Consumer(unitOfWork, repository);
            consumer.Action();
        }
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题