<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Agile at Work &#187; Command Query Separation</title>
	<atom:link href="http://www.agileatwork.com/tag/command-query-separation/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agileatwork.com</link>
	<description>by Michael Valenty</description>
	<lastBuildDate>Sat, 10 Sep 2011 14:35:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Custom Model Binder in ASP.NET MVC</title>
		<link>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/</link>
		<comments>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/#comments</comments>
		<pubDate>Thu, 31 Dec 2009 22:59:22 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Command Query Separation]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=298</guid>
		<description><![CDATA[The default model binder or DataAnnotationsModelBinder in ASP.NET MVC works well for simple data structures that basically map properties directly to form elements, but it quickly breaks down in a real world application. Take this simple scenario:

The built-in model binder can handle the easy fields like FirstName, LastName, and Email, but it doesn’t know how [...]]]></description>
			<content:encoded><![CDATA[<p>The default model binder or <font face="Courier New" size="2">DataAnnotationsModelBinder</font> in ASP.NET MVC works well for simple data structures that basically map properties directly to form elements, but it quickly breaks down in a real world application. Take this simple scenario:</p>
<p><img title="brimley" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="277" alt="brimley" src="http://www.agileatwork.com/wp-content/uploads/2009/12/brimley.png" width="253" border="0" /></p>
<p>The built-in model binder can handle the easy fields like <font face="Courier New" size="2">FirstName</font>, <font face="Courier New" size="2">LastName</font>, and <font face="Courier New" size="2">Email</font>, but it doesn’t know how to deal with the roles. This is where the custom model binder comes in:</p>
<pre class="prettyprint"><code>public class UserModelBinder : IModelBinder {
    private readonly IModelBinder binder;

    public UserModelBinder(IModelBinder binder) {
        this.binder = binder;
    }

    public object BindModel(ControllerContext controllerContext, ...) {
        var user = (User)binder.BindModel(controllerContext, bindingContext);
        AddRoles(user, controllerContext);
        return user;
    }

    private static void AddRoles(User user, ControllerContext controllerContext) {
        foreach (var role in GetRoles(controllerContext)) {
            user.Add(role);
        }
    }

    private static IEnumerable&lt;Role&gt; GetRoles(ControllerContext controllerContext) {
        var roles = controllerContext.HttpContext.Request["roles"];
        if (roles == null) yield break;
        foreach (var roleId in roles.Split(',')) {
            yield return (Role)Convert.ToInt32(roleId);
        }
    }
}</code></pre>
<p>And it gets wired-up in the Global.asax like this:</p>
<pre class="prettyprint"><code>var defaultBinder = new DataAnnotationsModelBinder();
ModelBinders.Binders.DefaultBinder = defaultBinder;
ModelBinders.Binders.Add(typeof(User), new UserModelBinder(defaultBinder));</code></pre>
<p>Because <font face="Courier New" size="2">UserModelBinder</font> is a decorator, it preserves the base functionality (like validation) of the default binder and only adds the part about mapping the roles. This is good stuff because it keeps construction of the model out of the controller. That&#8217;s the Single-Responsibility Principle in action.</p>
<h3>Command Query Separation</h3>
<p>The two functions <font face="Courier New" size="2">AddRoles</font>, and <font face="Courier New" size="2">GetRoles</font> are an example of command query separation (CQS). It would be easy to combine those two functions together and in fact that&#8217;s how it looked at first. So why bother separating them? Well it doesn&#8217;t <em>really</em> matter in this simple case, but it’s like how I tell my 3 year-old son to move his milk cup away from the edge of the table. I figure it’s a good habit that will prevent a few spills in the long run. The idea with CQS is there is a natural seam between finding objects and doing stuff with them. I buy that. I expect <font face="Courier New" size="2">GetRoles</font> to be more volatile than <font face="Courier New" size="2">AddRoles</font> or at least change for different reasons.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/custom-model-binder-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

