原文

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

表单如下:

这个表单能让用户输入关于组织的一些信息,包括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. [JSOI2008]Blue Mary的职员分配

    由于Blue Mary呕心沥血的管理,Blue Mary的网络公司蒸蒸日上.现在一共拥有了n名职员,可惜没有任何的金钱和声誉.平均每名每天职员都可以给公司带来x单位金钱或者y单位声誉(名利不能双全). ...

  2. P1972 HHのnecklace 离线+树状数组

    此题莫队可过 然而太难了...... 我在胡雨菲那看的解法,然后自己打了一波,调了一个错,上交,自信AC. 做法:离线,对于L排序. 每种颜色可能出现很多次,那么我们如何不算重复呢? 只需把[L,n] ...

  3. C#串口通信:2自动连接

    上次说到了协议的大致结构,这次我们来说说怎么去实现制动连接串口(当你把设备连上来之后,怎么去让软件自动去识别是否为目标设备,当然这需要上位机与下位机共同完成,这里我们只讨论上位机部分)先上协议: 帧头 ...

  4. (转)Java动态追踪技术探究

    背景:美团的技术沙龙分享的文章都还是很不错的,通俗易懂,开阔视野,后面又机会要好好实践一番. Java动态追踪技术探究 楔子 jsp的修改 重新加载不需要重启servlet.如何在不重启jvm的情况下 ...

  5. CF954F Runner's Problem(DP+矩阵快速幂优化)

    这题是一年前某场我参加过的Education Round codeforces的F题,当时我显然是不会的. 现在看看感觉应该是能做出的. 不扯了写题解: 考虑朴素的DP,在不存在障碍的情况下:f[i] ...

  6. css的简单学习笔记

    1.CSS的简介 *css :层叠样式表 **层叠: 一层一层. **样式表: 具有大量的属性和属性值 *使得页面的显示效果更加好. *css将网页内容和显示样式进行分离,提高了显示功能. *css不 ...

  7. arm-fsl-linux-gnueabi交叉编译器安装

    系统:Ubuntu 14.04 64bit 编译器gcc version 4.4.4 (4.4.4_09.06.2010) 解压编译器到相应路径(注:当我解压放到/home/cross_compile ...

  8. 一个很适合初学者的selenium教程

    http://www.cnblogs.com/hustar0102/p/5885115.html

  9. Level-IP(Linux userspace TCP/IP stack)

    转自:github.com/saminiir/level-ip Level-IP is a Linux userspace TCP/IP stack, implemented with TUN/TAP ...

  10. Go 的构建模式

    Go 的八种 Build Mode exe (静态编译) exe (动态链接 libc) exe (动态链接 libc 和非 Go 代码) pie 地址无关可执行文件(安全特性) c-archive  ...