有些刚接触CQRS的朋友容易被Event Sourcing带到沟里去,其实CQRS和Event Sourcing没有直接的关系,本篇文章我就介绍一种不用Event Sourcing的CQRS。
一、Comamnd和Query采用完全不同的组织思路。
二、Command执行后如果希望返回数据给UI,同步的使用Query进行查询。
三、Command和Query采用一个数据库。
下载地址:http://yunpan.cn/Q5bkD3wmVXBpv (访问密码:9c16)。
TestDynamicQueryController.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 using Happy.Query; 7 using Happy.Query.PetaPoco; 8 using Happy.Web.Mvc.Ext; 9 10 namespace Happy.Web.Mvc.Host.Controllers 11 { 12 public class TestDynamicQueryController : DynamicQueryController<TestDynamicQueryService> 13 { 14 protected override TestDynamicQueryService QueryService 15 { 16 get 17 { 18 return new TestDynamicQueryService(); 19 } 20 } 21 } 22 23 public class TestDynamicQueryService : PetaPocoDynamicQueryService 24 { 25 public TestDynamicQueryService() : 26 base(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + AppDomain.CurrentDomain.BaseDirectory + @"App_Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30", "System.Data.SqlClient", "Tests") 27 { } 28 } 29 }
TestCommandController.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 using Happy.Web.Mvc.Ext; 8 using Happy.Application; 9 using Happy.Command; 10 using Happy.Query; 11 using Happy.Web.Mvc.Host.Domain; 12 13 namespace Happy.Web.Mvc.Host.Controllers 14 { 15 public class TestCommandController : ExtJsController 16 { 17 public ActionResult Create(Test item) 18 { 19 CommandService.Current.Execute(new CreateTestCommand 20 { 21 Aggregate = item 22 }); 23 24 var query = DynamicQueryObject.Create("Id = @0", new object[] { item.Id }); 25 return this.NewtonsoftJson(new 26 { 27 success = true, 28 items = this.QueryService.SingleOrDefault(query) 29 }); 30 } 31 32 public ActionResult Update(Test item) 33 { 34 CommandService.Current.Execute(new UpateTestCommand 35 { 36 Aggregate = item 37 }); 38 39 var query = DynamicQueryObject.Create("Id = @0", new object[] { item.Id }); 40 return this.NewtonsoftJson(new 41 { 42 success = true, 43 items = this.QueryService.SingleOrDefault(query) 44 }); 45 } 46 47 private TestDynamicQueryService QueryService 48 { 49 get 50 { 51 return new TestDynamicQueryService(); 52 } 53 } 54 } 55 56 public class CreateTestCommand : SimpleCreateCommand<Test> { } 57 58 public class CreateTestCommandHandler : SimpleCreateCommandHandler<ITestUnitOfWork, ITestRepository, Test, CreateTestCommand> { } 59 60 public class UpateTestCommand : SimpleUpdateCommand<Test> { } 61 62 public class UpdateTestCommandHandler : SimpleUpdateCommandHandler<ITestUnitOfWork, ITestRepository, Test, UpateTestCommand> { } 63 }
采用这种最简单的CQRS,只是在代码层面进行职责的分离。基于Event Sourcing + In Memory + CQRS + DDD 的架构也是值得探讨和尝试的,这种架构汤雪华(http://www.cnblogs.com/netfocus/)有多难的研发和使用经验,估计他的最新框架ENode马上就发布了,到时我会用他的ENode写个Demo,ENode写的真的非常漂亮。