原文

来看看我目前的一个项目。这个是一个多租户的财务跟踪系统。有一个组织继承的关系。首先得新建一个组织。

表单如下:

这个表单能让用户输入关于组织的一些信息,包括active directory组,一个唯一的简写名。在客户端使用ajax确保active directory组存在。

POST Action如下:

// POST: Organizations/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(OrganizationEditorForm form)
{
Logger.Trace("Create::Post::{0}", form.ParentOrganizationId); if (ModelState.IsValid)
{
var command = new AddOrEditOrganizationCommand(form, ModelState);
var result = await mediator.SendAsync(command); if(result.IsSuccess)
return RedirectToAction("Index", new { Id = result.Result }); ModelState.AddModelError("", result.Result.ToString());
} return View(form);
}

基于mvc的模型绑定,绑定view model和做一些基础的基于datannotation的数据验证。如果验证失败,定向到表单页面并显示ModelState的错误。

接下来我构造了一个AddOrEditOrganzationCommand,它包含了view model和当前的ModelState。这能让我们将在服务端的验证结果附加到ModelState上。这个command对象只是简单的包含了我们需要的数据。

public class AddOrEditOrganizationCommand : IAsyncRequest<ICommandResult>
{
public OrganizationEditorForm Editor { get; set; }
public ModelStateDictionary ModelState { get; set; } public AddOrEditOrganizationCommand(OrganizationEditorForm editor,
ModelStateDictionary modelState)
{
Editor = editor;
ModelState = modelState;
}
}

这个command通过mediator来发送,返回一个结果。我的结果类型是 (SuccessResult 和 FailureResult) ,基于下面的接口:

public interface ICommandResult
{
bool IsSuccess { get; }
bool IsFailure { get; }
object Result { get; set; }
}

如果是成功的结果,重定向到用户最近创建的组织的详细页。如果失败,将失败的消息添加到ModelState中,并在form页面显示。

现在我们需要handler来处理命令。

public class OrganizationEditorFormValidatorHandler : CommandValidator<AddOrEditOrganizationCommand>
{
private readonly ApplicationDbContext context; public OrganizationEditorFormValidatorHandler(ApplicationDbContext context)
{
this.context = context;
Validators = new Action<AddOrEditOrganizationCommand>[]
{
EnsureNameIsUnique, EnsureGroupIsUnique, EnsureAbbreviationIsUnique
};
} public void EnsureNameIsUnique(AddOrEditOrganizationCommand message)
{
Logger.Trace("EnsureNameIsUnique::{0}", message.Editor.Name); var isUnique = !context.Organizations
.Where(o => o.Id != message.Editor.OrganizationId)
.Any(o => o.Name.Equals(message.Editor.Name,
StringComparison.InvariantCultureIgnoreCase)); if(isUnique)
return; message.ModelState.AddModelError("Name",
"The organization name ({0}) is in use by another organization."
.FormatWith(message.Editor.Name));
} public void EnsureGroupIsUnique(AddOrEditOrganizationCommand message)
{
Logger.Trace("EnsureGroupIsUnique::{0}", message.Editor.GroupName); var isUnique = !context.Organizations
.Where(o => o.Id != message.Editor.OrganizationId)
.Any(o => o.GroupName.Equals(message.Editor.GroupName,
StringComparison.InvariantCultureIgnoreCase)); if (isUnique)
return; message.ModelState.AddModelError("Group",
"The Active Directory Group ({0}) is in use by another organization."
.FormatWith(message.Editor.GroupName));
} public void EnsureAbbreviationIsUnique(AddOrEditOrganizationCommand message)
{
Logger.Trace("EnsureAbbreviationIsUnique::{0}",
message.Editor.Abbreviation); var isUnique = !context.Organizations
.Where(o => o.Id != message.Editor.OrganizationId)
.Any(o => o.Abbreviation.Equals(message.Editor.Abbreviation,
StringComparison.InvariantCultureIgnoreCase)); if (isUnique)
return; message.ModelState.AddModelError("Abbreviation",
"The Abbreviation ({0}) is in use by another organization."
.FormatWith(message.Editor.Name));
}
}

CommandValidator包含一些简单的帮助方法,用来迭代定义的验证方法并执行他们。每个验证方法执行一些特别的逻辑,并在出错的时候将错误消息添加到ModelState。

下面的command handler是将表单的信息存储到数据库中。

public class AddOrEditOrganizationCommandHandler : IAsyncRequestHandler<AddOrEditOrganizationCommand, ICommandResult>
{
public ILogger Logger { get; set; } private readonly ApplicationDbContext context; public AddOrEditOrganizationCommandHandler(ApplicationDbContext context)
{
this.context = context;
} public async Task<ICommandResult> Handle(AddOrEditOrganizationCommand message)
{
Logger.Trace("Handle"); if (message.ModelState.NotValid())
return new FailureResult("Validation Failed"); if (message.Editor.OrganizationId.HasValue)
return await Edit(message); return await Add(message);
} private async Task<ICommandResult> Add(AddOrEditOrganizationCommand message)
{
Logger.Trace("Add"); var organization = message.Editor.BuildOrganiation(context); context.Organizations.Add(organization); await context.SaveChangesAsync(); Logger.Information("Add::Success Id:{0}", organization.Id); return new SuccessResult(organization.Id);
} private async Task<ICommandResult> Edit(AddOrEditOrganizationCommand message)
{
Logger.Trace("Edit::{0}", message.Editor.OrganizationId); var organization = context.Organizations
.Find(message.Editor.OrganizationId); message.Editor.UpdateOrganization(organization); await context.SaveChangesAsync(); Logger.Information("Edit::Success Id:{0}", organization.Id); return new SuccessResult(organization.Id);
}
}

这个handle非常简单。首先检查上一次的验证结果,如果失败直接返回失败结果。然后根据ID判断是执行新增还是编辑方法。

现在我们还没有为组织启用或禁用feature。我想将保存组织信息和处理feature的代码逻辑分隔开。

因此我新增一个UpdateOrganizationFeaturesPostHandler来处理feature。

public class UpdateOrganizationFeaturesPostHandler : IAsyncPostRequestHandler<AddOrEditOrganizationCommand, ICommandResult>
{
public ILogger Logger { get; set; } private readonly ApplicationDbContext context; public UpdateOrganizationFeaturesPostHandler(ApplicationDbContext context)
{
this.context = context;
} public async Task Handle(AddOrEditOrganizationCommand command,
ICommandResult result)
{
Logger.Trace("Handle"); if (result.IsFailure)
return; var organization = await context.Organizations
.Include(o => o.Features)
.FirstAsync(o => o.Id == (int) result.Result); var enabledFeatures = command.Editor.EnabledFeatures
.Select(int.Parse).ToArray(); //disable features
organization.Features
.Where(f => !enabledFeatures.Contains(f.Id))
.ToArray()
.ForEach(f => organization.Features.Remove(f)); //enable features
context.Features
.Where(f => enabledFeatures.Contains(f.Id))
.ToArray()
.ForEach(organization.Features.Add); await context.SaveChangesAsync();
}
}

Create的Get Action如下:

// GET: Organizations/Create/{1}
public async Task<ActionResult> Create(int? id)
{
Logger.Trace("Create::Get::{0}", id); var query = new OrganizationEditorFormQuery(parentOrganizationId: id);
var form = await mediator.SendAsync(query);
return View(form);
}

模型绑定如下:

[ModelBinderType(typeof(OrganizationEditorForm))]
public class OrganizationEditorFormModelBinder : DefaultModelBinder
{
public ILogger Logger { get; set; } private readonly ApplicationDbContext dbContext; public OrganizationEditorFormModelBinder(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
} public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
Logger.Trace("BindModel"); var form = base.BindModel(controllerContext, bindingContext)
.CastOrDefault<OrganizationEditorForm>(); if (form.ParentOrganizationId.HasValue)
form.ParentOrganization = dbContext.Organizations
.FirstOrDefault(o => o.Id == form.ParentOrganizationId); return form; }
}

[译]A NON-TRIVIAL EXAMPLE OF MEDIATR USAGE的更多相关文章

  1. [译]ASP.NET Core中使用MediatR实现命令和中介者模式

    作者:依乐祝 原文地址:https://www.cnblogs.com/yilezhu/p/9866068.html 在本文中,我将解释命令模式,以及如何利用基于命令模式的第三方库来实现它们,以及如何 ...

  2. [译]MediatR, FluentValidation, and Ninject using Decorators

    原文 CQRS 我是CQRS模式的粉丝.对我来说CQRS能让我有更优雅的实现.它同样也有一些缺点:通常需要更多的类,workflow不总是清晰的. MediatR MediatR的文档非常不错,在这就 ...

  3. [译]使用mediatR的notification来扩展的的应用

    原文 你不希望在controller里面出现任何领域知识 开发者经常有这样的疑问"这个代码应该放在哪呢?"应该使用仓储还是query类?.... 怎么去实现职责分离和单一职责呢? ...

  4. [译]使用Command模式和MediatR简化你的控制器

    原文 你希望保持你的controller足够简单. 你的controller越来越臃肿,你听说command模式是一个给controller瘦身的解决方案. 但是你不知道command模式是否适合你的 ...

  5. 【译】Android NDK API 规范

    [译]Android NDK API 规范 译者按: 修改R代码遇到Lint tool的报错,搜到了这篇文档,aosp仓库地址:Android NDK API Guidelines. 975a589 ...

  6. Drupal与大型网站架构(译)- Large-Scale Web Site Infrastructure and Drupal

    Drupal与大型网站架构(译)- Large-Scale Web Site Infrastructure and Drupal Linuxjournal 网站经典文章翻译,原文地址: Large-S ...

  7. 【译】延迟加载JavaScript

    [译]延迟加载JavaScript 看到一个微信面试题引发的血案 --[译] 什么阻塞了 DOM?中提到的一篇文章,于是决定看下其博客内容,同时翻译下来留作笔记,因英文有限,如有不足之处,欢迎指出.同 ...

  8. REST API设计指导——译自Microsoft REST API Guidelines(四)

    前言 前面我们说了,如果API的设计更规范更合理,在很大程度上能够提高联调的效率,降低沟通成本.那么什么是好的API设计?这里我们不得不提到REST API. 关于REST API的书籍很多,但是完整 ...

  9. 译:4.RabbitMQ Java Client 之 Routing(路由)

    在上篇博文 译:3.RabbitMQ 之Publish/Subscribe(发布和订阅)  我们构建了一个简单的日志系统 我们能够向许多接收者广播日志消息. 在本篇博文中,我们将为其添加一个功能 - ...

随机推荐

  1. centos7/rhel7下配置PXE+Kickstart自动安装linux系统

    应用场景:临时安装一个系统或者批量安装linux系统,无需人工介入选择下一步,减少在安装系统上的时间浪费,提高工作效率. DHCP + TFTP + Syslinux + FTP + Kickstar ...

  2. 洛谷P3265 装备购买

    这个大毒瘤题....居然反向卡精度.... 别的题eps要开小,这个毒瘤要开大... 我一开始是1e-12,挂的奇惨无比,50分...... 然后改成1e-7,就70分了... 1e-5 90分 1e ...

  3. JavaScript深入之变量对象

    前言 在上篇<javascript深入之执行上下文栈>中讲到,当javascript代码执行一段可执行代码(executable code)时,会创建对应的执行上下文(execution ...

  4. C# http请求带请求头部分

    直接上代码 前台调用: <script type="text/javascript"> function zLoginCheck() { var Account = ' ...

  5. 安全测试之Top 10 漏洞的分析

    1. 问题:没有被验证的输入  测试方法: 数据类型(字符串,整型,实数,等) 允许的字符集 最小和最大的长度 是否允许空输入 参数是否是必须的 重复是否允许 数值范围 特定的值(枚举型) 特定的模式 ...

  6. windows 文件夹下所有文件名称

    dir dir /b 没有其它信息 dir /b >>xxx.txt 保存到txt

  7. spring cron表达式(定时器)

    转: spring cron表达式(定时器) 写定时器时用到,记录一下: Cron表达式是一个字符串,字符串以5或6个空格隔开,分开工6或7个域,每一个域代表一个含义,Cron有如下两种语法 格式:  ...

  8. tensorflow中tf.ConfigProto()用法解释

    在看C3D代码的时候,看见有一段代码是 config = tf.ConfigProto()#主要是配置tf.Session的运行方式,GPU还是CPU,在这里选择的是GPU的运行方式 config.g ...

  9. VUE通过id从列表页跳转到相对的详情页

    新闻列表页面: 在这里我用a标签进行跳转,在vue里面可以这样写<router-link></router-link> 1 <router-link :to=" ...

  10. UI动画的一些制作过程

    选中将要制作的3D物体,window----Animation----录制,选中的AddKey在之间的节点前点左键.