EntityFramework用法探索(六)静态Repository

上文中,我们引入了Unity,用来帮助构建各个Repository和UnitOfWork。

同时,我们将UnityContainer注入到了ServiceLocator的实现中,

1       UnityServiceLocator locator = new UnityServiceLocator(container);
2       ServiceLocator.SetLocatorProvider(() => locator);

如果表数量过多,将IxxxRepository注入到业务类中过于繁琐,为寻求简洁办法,此处引入ServiceLocator和静态类,虽然这两种方式都不太适合单元测试。

 1   public static class Repository
 2   {
 3     public static IRepository<Customer> Customers
 4     {
 5       get { return ServiceLocator.Current.GetInstance<IRepository<Customer>>(); }
 6     }
 7 
 8     public static void Commit()
 9     {
10       ServiceLocator.Current.GetInstance<IUnitOfWork>().Commit();
11     }
12   }

如果我们有新的表定义,仅需新增一个属性即可。例如新增个供应商表Supplier。

1     public static IRepository<Supplier> Suppliers
2     {
3       get { return ServiceLocator.Current.GetInstance<IRepository<Supplier>>(); }
4     }

这样,我们的业务代码可以变得简洁些,

 1     public void InsertCustomer(DomainModels.Customer customer)
 2     {
 3       Customer entity = Mapper.Map<DomainModels.Customer, Customer>(customer);
 4 
 5       Repository.Customers.Insert(entity);
 6       Repository.Commit();
 7 
 8       customer.Id = entity.Id;
 9     }
10 
11     public void UpdateCustomer(DomainModels.Customer customer)
12     {
13       Customer entity = Repository.Customers.Query().Single(c => c.Id == customer.Id);
14 
15       entity.Name = customer.Name;
16       entity.Address = customer.Address;
17       entity.Phone = customer.Phone;
18 
19       Repository.Customers.Update(entity);
20 
21       Repository.Commit();
22     }

完整代码和索引

EntityFramework用法探索系列

完整代码下载

原文地址:https://www.cnblogs.com/gaochundong/p/entityframework_usage_static_repository.html