DDD领域驱动之干货(三)完结篇!
首先这里发一下结构图,因为是重写的,但是代码都是一样所有如下:

这里我先说一下看了大部分的DDD文章都是采用的WCF做服务,这里呢我用的是webapi做服务,WCF和WEBAPI的区别可以去百度下。
好了。现在我们看下automapper的具体实现。
因为automapper又一个Profile类,而我们自己写的类去继承这个类,所有如下图:

上图是创建映射关系,下面就去添加映射

这些做完了 我们现在需要使用

这里的dto类型是CostomDTO 也就是数据传输对象。
下面我们来看下工作单元,下面我直接贴代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.UnitOfWork
{
/// <summary>
/// 表示所有集成该接口都是工作单元的一种实现
/// </summary>
public interface IUnitOfWork
{
/// <summary>
/// 提交
/// </summary>
void Commit(); /// <summary>
/// 异步提交
/// </summary>
/// <returns></returns>
Task CommitSyncAsync(); /// <summary>
/// 回滚
/// </summary>
void Rollback(); /// <summary>
/// 已经提交过了
/// </summary>
bool Committed { get; } /// <summary>
/// 事务支持
/// </summary>
//bool DistributedTransactionSupported { get; }
}
}
这是IUnitOfWork接口代码。
using KuRuMi.Mio.DoMainModel.BaseModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.UnitOfWork
{
public interface IUnitOfWorkContext : IUnitOfWork, IDisposable
{
/// <summary>
/// 将指定的聚合根标注为“新建”状态。
/// </summary>
/// <typeparam name="TAggregateRoot">需要标注状态的聚合根类型。</typeparam>
/// <param name="obj">需要标注状态的聚合根。</param>
void RegisterNew<TAggregateRoot>(TAggregateRoot obj)
where TAggregateRoot : class, IAggregateRoot;
/// <summary>
/// 将指定的聚合根标注为“更改”状态。
/// </summary>
/// <typeparam name="TAggregateRoot">需要标注状态的聚合根类型。</typeparam>
/// <param name="obj">需要标注状态的聚合根。</param>
void RegisterModified<TAggregateRoot>(TAggregateRoot obj)
where TAggregateRoot : class, IAggregateRoot;
/// <summary>
/// 将指定的聚合根标注为“删除”状态。
/// </summary>
/// <typeparam name="TAggregateRoot">需要标注状态的聚合根类型。</typeparam>
/// <param name="obj">需要标注状态的聚合根。</param>
void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj)
where TAggregateRoot : class, IAggregateRoot;
}
}
这是IUnitOfWorkContext接口代码
因为我是基于EF实现的所以这里多了一层EF的工作单元代码
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.UnitOfWork
{
/// <summary>
/// 表示是EF仓储的一种实现
/// </summary>
public interface IEFUnitOfWorkContext : IUnitOfWorkContext
{
DbContext Context { get; }
}
}
完成这里接下来就是工作单元的实现类
using KuRuMi.Mio.DoMainModel.BaseModel;
using KuRuMi.Mio.DoMain.Infrastructure;
using KuRuMi.Mio.DoMain.Repository.EFRepository;
using KuRuMi.Mio.DoMain.Repository.UnitOfWork;
using System.Data.Entity;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.BaseUnitOfWork
{
public class UnitOfWorkContext: DisposableObject, IEFUnitOfWorkContext
{
private KurumiMioDbContext kurumi = null; public UnitOfWorkContext() {
kurumi = new KurumiMioDbContext();
} public DbContext Context { get { return kurumi; } } #region 工作单元
public bool Committed { get; protected set; } /// <summary>
/// 同步提交
/// </summary>
public void Commit()
{
if (!Committed)
{
//kurumi.Value.GetValidationErrors();
Context.SaveChanges();
Committed = true;
}
} /// <summary>
/// 异步提交
/// </summary>
/// <returns></returns>
public async Task CommitSyncAsync()
{
if (!Committed)
{
await Context.SaveChangesAsync();
Committed = true;
}
}
/// <summary>
/// 释放资源
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!Committed)
Commit();
Context.Dispose();
kurumi.Dispose();
}
} /// <summary>
/// 回滚
/// </summary>
public void Rollback()
{
Committed = false;
}
#endregion #region IEFUnitOfWorkContext接口
/// <summary>
/// 删除未提交
/// </summary>
/// <typeparam name="TAggregateRoot"></typeparam>
/// <param name="obj"></param>
public void RegisterDeleted<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class, IAggregateRoot
{
Context.Entry(obj).State = EntityState.Deleted;
Committed = false;
} /// <summary>
/// 修改未提交
/// </summary>
/// <typeparam name="TAggregateRoot"></typeparam>
/// <param name="obj"></param>
public void RegisterModified<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class, IAggregateRoot
{
if (Context.Entry(obj).State == EntityState.Detached)
{
Context.Set<TAggregateRoot>().Attach(obj);
}
Context.Entry(obj).State = EntityState.Modified;
Committed = false;
} /// <summary>
/// 新建未提交
/// </summary>
/// <typeparam name="TAggregateRoot"></typeparam>
/// <param name="obj"></param>
public void RegisterNew<TAggregateRoot>(TAggregateRoot obj) where TAggregateRoot : class, IAggregateRoot
{
var state = Context.Entry(obj).State;
if (state == EntityState.Detached)
{
Context.Entry(obj).State = EntityState.Added;
}
Committed = false;
}
#endregion
}
}
现在呢就是我的仓储,因为是聚合根的缘故,所以聚合后的根有自己特有的仓储代码如下。
using KuRuMi.Mio.DoMainModel.Model;
using KuRuMi.Mio.DoMainModel.Repositories;
using KuRuMi.Mio.DoMain.Repository.EFRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.ModelRepository
{
public class CostomRepositoryImpl :RepositoryImpl<Costom>, ICostomRepository
{
public KurumiMioDbContext context => lazy.Context as KurumiMioDbContext;
public Costom GetAll()
{
string sql = "select * from Costom";
return context.costom.SqlQuery(sql).FirstOrDefault();
}
}
}
然后是我的总仓储的实现
using KuRuMi.Mio.DoMainModel.BaseModel;
using KuRuMi.Mio.DoMainModel.Repositories;
using KuRuMi.Mio.DoMain.Repository.BaseUnitOfWork;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace KuRuMi.Mio.DoMain.Repository.EFRepository
{
/// <summary>
/// 仓储的泛型实现
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class RepositoryImpl<TEntity> : IRepository<TEntity> where TEntity : AggregateRoot
{
public readonly UnitOfWorkContext lazy = null;
public RepositoryImpl()
{
lazy = new UnitOfWorkContext(); } /// <summary>
/// 新增
/// </summary>
/// <param name="aggregateRoot"></param>
public virtual void Add(TEntity aggregateRoot)
{
lazy.RegisterNew<TEntity>(aggregateRoot);
lazy.Commit();
}
/// <summary>
/// 通过key获取聚合根
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public virtual TEntity GetKey(Guid key)
{
return lazy.Context.Set<TEntity>().Find(key);
} public virtual IQueryable<TEntity> LoadAll(Expression<Func<TEntity, bool>> predicate)
{
return lazy.Context.Set<TEntity>().Where(predicate).AsQueryable();
}
/// <summary>
/// 复杂查询
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public virtual IQueryable<TEntity> LoadForSql(string sql)
{
return lazy.Context.Set<TEntity>().SqlQuery(sql).AsQueryable();
} public virtual IEnumerable<TEntity> LoadListAll(Expression<Func<TEntity, bool>> predicate)
{
return lazy.Context.Set<TEntity>().Where(predicate).ToList();
}
/// <summary>
/// 复杂查询
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public virtual IEnumerable<TEntity> LoadListForSql(string sql)
{
return lazy.Context.Set<TEntity>().SqlQuery(sql).ToList();
} /// <summary>
/// 删除
/// </summary>
/// <param name="aggregateRoot"></param>
public virtual void Remove(TEntity aggregateRoot)
{
lazy.RegisterDeleted<TEntity>(aggregateRoot);
lazy.Commit();
} /// <summary>
/// 修改
/// </summary>
/// <param name="aggregateRoot"></param>
public virtual void Update(TEntity aggregateRoot)
{
lazy.RegisterModified<TEntity>(aggregateRoot);
lazy.Commit();
}
}
}
现在回到我们的服务层
系统初始化我采用的是autofac,至于为什么不采用unity,博主个人喜欢用autofac原因轻量,简单。
好了下面献上我的初始化系统类。
using KuRuMi.Mio.DataObject.AutoMapperDTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using KuRuMi.Mio.DoMain.Infrastructure.IocManager;
using KuRuMi.Mio.DoMainModel.Repositories;
using Autofac; namespace KuRuMi.Mio.BootStarp
{ /// <summary>
/// 系统初始化
/// </summary>
public class OptionBootStarp
{
protected IEnumerable<Assembly> assembles { get; }
protected IIocManager ioc { get; }
public OptionBootStarp(IEnumerable<Assembly> ass)
{
assembles = ass;
ioc = IocManager.Instance;
}
protected IEnumerable<Type> Repository => assembles.SelectMany(a => a.ExportedTypes.Where(t => t.GetInterfaces().Contains(typeof(IBaseRepository))));
protected IEnumerable<Type> BaseDTO => assembles.SelectMany(a => a.ExportedTypes.Where(t => t.GetInterfaces().Contains(typeof(IAutoMapper)))); protected IEnumerable<Type> Services => assembles.SelectMany(a => a.ExportedTypes.Where(t => t.GetInterfaces().Contains(typeof(IService))));
/// <summary>
/// 预加载
/// </summary>
public void Initialize()
{
//加载所有DTO
BaseDTO.ToList().ForEach(s=> {
var dtpye= Activator.CreateInstance(s) as IAutoMapper;
ioc.build.RegisterInstance(dtpye).As<MapperConfigurationImpl>().SingleInstance().PropertiesAutowired();
});
//加载所有的仓储
Repository.ToList().ForEach(s => {
if (s.IsClass == true && s.IsGenericType == false)
{
var dtpye = Activator.CreateInstance(s);
ioc.build.RegisterType(dtpye.GetType()).As(dtpye.GetType());
}
});
//加载所有服务
Services.ToList().ForEach(s =>
{
if (s.IsClass == true)
{
var stype = Activator.CreateInstance(s);
ioc.build.RegisterType(stype.GetType()).As(stype.GetType());
}
});
PostInit();
}
/// <summary>
/// 注入
/// </summary>
protected void PostInit() {
ioc.CompleteBuild();
}
} }
下面贴上测试结果,WEB端请求的是webapi其中涉及到跨域请求问题,采用的是微软的cors包。

需要代码的同学点这里。
PS:采用了autofac IOC框架 automapper 映射框架 Log4Net 日志 ORM是EF 用的是codefirst 运行的时候只需要改web.config的数据库连接就可以了。
链接: 百度 密码: 3baw
DDD领域驱动之干货(三)完结篇!的更多相关文章
- DDD领域驱动之干货(四)补充篇!
距离上一篇DDD系列完结已经过了很长一段时间,项目也搁置了一段时间,想想还是继续完善下去. DDD领域驱动之干货(三)完结篇! 上一篇说到了如何实现uow配合Repository在autofac和au ...
- DDD 领域驱动设计-三个问题思考实体和值对象(续)
上一篇:DDD 领域驱动设计-三个问题思考实体和值对象 说实话,整理现在这一篇博文的想法,在上一篇发布出来的时候就有了,但到现在才动起笔来,而且写之前又反复读了上一篇博文的内容及评论,然后去收集资料, ...
- DDD 领域驱动设计-三个问题思考实体和值对象
消息场景:用户 A 发送一个消息给用户 B,用户 B 回复一个消息给用户 A... 现有设计:消息设计为实体并为聚合根,发件人.收件人设计为值对象. 三个问题: 实体最重要的特性是什么? Messag ...
- [转] DDD领域驱动设计(三) 之 理论知识收集汇总
最近一直在学习领域驱动设计(DDD)的理论知识,从网上搜集了一些个人认为比较有价值的东西,贴出来和大家分享一下: 我一直觉得不要盲目相信权威,比如不能一谈起领域驱动设计,就一定认为国外的那个Eric ...
- DDD领域驱动之干货 (一)
说道DDD不得不说传统的架构与DDD的架构区别. 传统的架构不外乎就是三层,而在这三层里面又不断的细分,始终没有达到想要的效果,那么为什么当时还是采用三层. 当然在DDD没有提出的时候三层是大多数人的 ...
- DDD领域驱动之干货(二)
基于仓储的实现 1.前言:本着第一节写的有些糊涂,主要是自己喜欢实干,不太喜欢用文字表述,就这样吧.下面切入正题. 博客园里面有很多的大佬,我这里就不一一解释概览,有兴趣的朋友可以去看大佬们写的 ...
- [0] DDD领域驱动设计(三) 之 聚合(根)、实体、值对象
1. 聚合根.实体.值对象的区别? 从标识的角度: 聚合根具有全局的唯一标识,而实体只有在聚合内部有唯一的本地标识,值对象没有唯一标识,不存在这个值对象或那个值对象的说法: 从是否只读的角度 ...
- DDD领域驱动之干活(四)补充篇!
距离上一篇DDD系列完结已经过了很长一段时间,项目也搁置了一段时间,想想还是继续完善下去. DDD领域驱动之干货(三)完结篇! 上一篇说到了如何实现uow配合Repository在autofac和au ...
- DDD 领域驱动设计-“臆想”中的实体和值对象
其他博文: DDD 领域驱动设计-三个问题思考实体和值对象 DDD 领域驱动设计-三个问题思考实体和值对象(续) 以下内容属于博主"臆想",如有不当,请别当真. 扯淡开始: 诺兰的 ...
随机推荐
- C++中的类继承(2)派生类的默认成员函数
在继承关系里面, 在派生类中如果没有显示定义这六个成员 函数, 编译系统则会默认合成这六个默认的成员函数. 构造函数. 调用关系先看一段代码: class Base { public : Base() ...
- 使用Dockerfile制作自己的Docker镜像
一.背景 一直以来的开发流程都是先从Docker Hub中获取到基础镜像,之后在这个镜像的基础上做开发,以满足一定的需求或者提供某种服务,并由此产生新的镜像,然后就可以push到Docker Hub中 ...
- 【Linux配置】vim配置文件内容
vim的配置 文件:~/.vimrc 在自己的家目录中的.vimrc文件进行编辑配置 设置如下: set nu "序号 set tabstop= "tab键的大小 set show ...
- PHP 魔术方法 __call 与 __callStatic 方法
PHP 魔术方法 __call 与 __callStatic 方法 PHP 5.3 后新增了 __call 与 __callStatic 魔法方法. __call 当要调用的方法不存在或权限不足时,会 ...
- Ajax 与 Comet
Ajax技术的核心是XMLHttpRequest对象(简称XHR). XMLHttpRequest对象 在浏览器中创建XHR对象要像下面这样,使用XMLHttpRequest构造函数. var xhr ...
- Swift中枚举的总结以及使用
枚举定义了一组具有相关性的数据,是开发者可以再带吗中以一个安全的方式来使用这些值,以又助于提供代码的可读性. 在Swift中,枚举可以分成两种:任意类型的枚举和指定类型的枚举,结构如下: //任意类型 ...
- 从网络通信角度谈web性能优化
衡量一个网站的性能有多个指标,DNS解析时间,TCP链接时间,HTTP重定向时间,等待服务器响应时间等等,从用户角度来看,就可以归结为该网站访问速度的快慢.也就是说性能等于网站的访问速度. 早些年Am ...
- WPF 杂谈——入门介绍
对于WPF的技术笔者是又爱又恨.现在WPF的市场并不是很锦气.如果以WPF来吃饭的话,只怕会饿死在街头.同时现在向面WEB开发更是如火冲天.所以如果是新生的话,最好不要以WPF为主.做为选择性来学习一 ...
- html php javascript 页面跳转
<!-- html标签跳转 --><meta http-equiv="refresh" content="3;url=http://localhost/ ...
- .net之抽象工厂模式
//抽象工厂 //抽象食物 namespace abstractFactory{ public abstract class food { public abstract void Food(); } ...