Using the Generic repository/Unit of work pattern in large projects

前端 未结 2 1232
悲&欢浪女
悲&欢浪女 2021-02-04 21:52

I\'m working on a quite large application. The domain has about 20-30 types, implemented as ORM classes (for example EF Code First or XPO, doesn\'t matter for the question). I\'

2条回答
  •  Happy的楠姐
    2021-02-04 22:31

    Building on my comments above and on top of the answer here.

    With a slightly modified unit of work abstraction

    public interface IMyUnitOfWork
    {
        void CommitChanges();
        void DropChanges();
    
        IRepository Repository();
    }
    

    You can expose named repositories and specific repository methods with extension methods

    public static class MyRepositories
    {
        public static IRepository Users(this IMyUnitOfWork uow)
        {
            return uow.Repository();
        }
    
        public static IRepository Products(this IMyUnitOfWork uow)
        {
            return uow.Repository();
        }
    
        public static IEnumerable GetUsersInRole(
            this IRepository users, string role)
        {
            return users.AsQueryable().Where(x => true).ToList();
        }
    
        public static IEnumerable GetInCategories(
            this IRepository products, params string[] categories)
        {
            return products.AsQueryable().Where(x => true).ToList();
        }
    }
    

    That provide access the data as required

    using(var uow = new MyUnitOfWork())
    {
        var allowedUsers = uow.Users().GetUsersInRole("myRole");
    
        var result = uow.Products().GetInCategories("scarf", "hat", "trousers");
    }
    

提交回复
热议问题