Latest Replies
Monday
Apr052010

ASP.NET MVC and CQRS

It's interesting to see, how ASP.NET MVC plays out nicely with the Command-Query Responsibility Segregation (CQRS) concepts, while making web projects much easier.

For example, in the view methods, we don't need to have explicit view models or complex data transformations. All the data is already prepared for the consumption by the UI side. You just need to grab the query data and bind it to the View. Our view actions in CQRS world can look as simple as:

public class SomeController
{
  public ActionResult Details(Guid id)
  {
    var viewModel = cache.Load<SomeModel>(id);
    return View("details", viewModel);
  }

or for the lists:

  public ActionResult List(Guid id, int? page)
  {
    var paged = cache.List<SomeModel>((where, s) =>
    {
      where.Equals(() => s.ParentId, id);
      where.PageIs(() => s.Index, page, 20);
    });

    return View("list", paged);
  }

with the simplest form of View:

<%= Html.Grid(Model).AutoGenerateColumns() %>

Command side of the ASP.NET MVC application can be really simple, too. Basically all we need to do is to pre-validate command parameters and send it to the bus.

  public ActionResult Post(SomeForm form)
  {
    // validate the input data
    var command = new SomeCommand(form.SomeProperty, form.AnoterProperty);
    bus.Send(command);
    return View("SomeNextView");
  }
}

Controller here just sends the command without bothering what happens next. So CQRS just leaves ASP.NET MVC to do the job it was designed for - presentation, while making the base code rather boring.

Related Posts:

« NServiceBus and Windows Azure Challenges | Main | iPad for Enterprise Developer »