DDD实战4 实现产品仓储

a.要实现仓储,首先要定义仓储接口。在领域层定义仓储接口,IProductRepository.cs。

public interface IProductRepository
    {
        void CreateProduct<T>(T productspu) where T:class,IAggregationRoot;
    }

 产品持久化仓储的实现不应当在领域层实现,因为领域就和仓储实现紧密的绑定在了一起,导致业务和技术没有分离。之所以把接口定义在领域层是因为,领域层对数据的访问只要调用接口就行了。

b.在基础结构层中新建项目实现仓储实现,在基础结构层新建项目取名DDD.Repositories,以后将所有的仓储的实现都写在这个项目中。

 领域层是核心层,仓储应该依赖领域层,所以在此,为DDD.Repositories添加依赖项目——Product.Domain。

c.在DDD.Repositories项目下添加文件夹,取名ProductRepositories,在此文件夹内放置针对产品的仓储,在此文件夹下面添加EFCore针对产品聚合仓储的实现ProductEFCorerepositoy

public class ProductEFCoreRepository : IProductRepository
    {
        private readonly DbContext dbcontext;

        public ProductEFCoreRepository(DbContext dbcontext)
        {
            this.dbcontext = dbcontext;
        }
        public void CreateProduct<T>(T productspu) where T : class, IAggregationRoot
        {
//这里的ProductEFCoreContext就是上节 在产品领域层创建的ProductEFCoreContext类,我们用它生成的数据库
var db = dbcontext as ProductEFCoreContext; var newproductspu = productspu as ProductSPU; try { db.ProductSPU.Add(newproductspu); } catch (Exception ex) { throw ex; } } }

 以上就是产品仓储的实现,它和领域的业务逻辑是完全分离的,只是在仓储里面会用到领域对象,领域对象是业务的核心。

原文地址:https://www.cnblogs.com/wholeworld/p/8862568.html