<?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>Technical Jargon &#187; aspnetmvc</title>
	<atom:link href="http://www.jeremyskinner.co.uk/tag/aspnetmvc/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jeremyskinner.co.uk</link>
	<description>Did you notice the information bar?</description>
	<lastBuildDate>Mon, 08 Mar 2010 20:17:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Limitations of MVC2&#8217;s ModelValidatorProviders</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 11:08:40 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=274</guid>
		<description><![CDATA[
Update 6 Feb 2010: Most of the issues that I&#8217;ve mentioned here have been addressed in MVC2 RC2. See this post for details.


One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when they [...]]]></description>
			<content:encoded><![CDATA[<p>
<strong>Update 6 Feb 2010:</strong> Most of the issues that I&#8217;ve mentioned here have been addressed in MVC2 RC2. See <a href="http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/">this post</a> for details.
</p>
<p>
One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when they are passed to action parameters.
</p>
<p>
I wanted to try and write one of these for <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> (see <a href="http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/">this post</a>) but after trying this it has become quite clear that the ModelValidatorProvider API does have some limitations which have caused me some problems.
</p>
<h3>Problem 1: Property-level validation</h3>
<p>
To understand this problem, first we need to look at how different validation frameworks perform their work.
</p>
<p>
When using FluentValidation, the validators work against a pre-populated object. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Customer<span style="color: #000000;">&#123;</span> 
  <span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">CreditLimit</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GreaterThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
var customer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer <span style="color: #000000;">&#123;</span> CreditLimit <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span>, Surname <span style="color: #008000;">=</span> <span style="color: #0600FF;">null</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
var validator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var results <span style="color: #008000;">=</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>customer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
You cannot reliably validate individual properties by themselves because they may have dependencies on *other* properties being set. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEqual</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Forename</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
This rule says tht the Surname and Forename properties must not be equal. In this case, you cannot validate the surname property by itself without having first set the value for the Forename property. Other validation frameworks (eg the Castle Project&#8217;s validation attributes) work in a similar way.
</p>
<p>
The MVC Framework&#8217;s DefaultModelBinder is primarily designed to work with the System.ComponentModel.DataAnnotations attributes. These work in a different way &#8211; they validate individual values, not the entire object.  To support this, the DefaultModelBinder allows validating both the individual property values (in the OnPropertyValidated method) as well as validating the entire instance (in the OnModelUpdated method).
</p>
<p>
Here are the relevant methods from DefaultModelBinder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnPropertyValidated - called for each property being bound.</span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnPropertyValidated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    ModelMetadata propertyMetadata <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">PropertyMetadata</span><span style="color: #000000;">&#91;</span>propertyDescriptor.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    propertyMetadata.<span style="color: #0000FF;">Model</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> modelStateKey <span style="color: #008000;">=</span> CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, propertyMetadata.<span style="color: #0000FF;">PropertyName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// run validation</span>
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> propertyMetadata.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">Model</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>modelStateKey, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// only add a &quot;value was required&quot; error message if there were no validation errors</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">IsValidField</span><span style="color: #000000;">&#40;</span>modelStateKey<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>value <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>TypeHelpers.<span style="color: #0000FF;">TypeAllowsNullValue</span><span style="color: #000000;">&#40;</span>propertyDescriptor.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>modelStateKey, GetValueRequiredResource<span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnModelUpdated - called once the entire object has been bound. </span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnModelUpdated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    IDataErrorInfo errorProvider <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">Model</span> <span style="color: #0600FF;">as</span> IDataErrorInfo<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>errorProvider <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         <span style="color: #FF0000;">string</span> errorText <span style="color: #008000;">=</span> errorProvider.<span style="color: #0000FF;">Error</span><span style="color: #008000;">;</span>
         <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>errorText<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, errorText<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
          <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>IsModelValid<span style="color: #000000;">&#40;</span>bindingContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        return<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> bindingContext.<span style="color: #0000FF;">ModelMetadata</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
On first glance, this looks like it will work. When OnPropertyValidated calls GetValidators, I can return an empty collection of validators and do all of my work in a single validator in OnModelUpdated. Unfortunately, this does not work.
</p>
<p>
See the end of OnPropertyValidated? Here, it checks if there have been any validation errors for the property and if not then it <strong>will go ahead and run its own built-in field validation anyway for non-nullable value types</strong> &#8211; it will put a message saying &#8220;A value was required&#8221; into ModelState. And you can&#8217;t turn this off. The *only way* to stop this built-in validation is to support property-level validation in your custom ValidatorProvider. Not very useful if the underlying framework does not support this.
</p>
<p>
To work around the above issue, I ended up adding property-level validation to FluentValidation, but this is not a completely reliable solution because of the issues related to cross-property validation I mentioned above.
</p>
<h3>Problem 2: The DataAnnotationsModelValidatorProvider is greedy</h3>
<p>
The next problem that I ran into is that the DataAnnotationsModelValidatorProvider will always run required field validation, even if you&#8217;re not using the DataAnnotations attributes!
</p>
<p>Here is an example that uses FluentValidation to validate an object where a null value is being bound to a non-nullable value type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Validator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>FooValidator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Foo <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> FooValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Foo<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> FooValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEmpty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//fails - 2 instead of 1</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This test fails because there are two error messages rather than one:
</p>
<pre>The Id field is required.
'Id' should not be empty.
</pre>
<p>
&#8230;the first of these errors comes from the DataAnnotationsModelValidatorProvider <strong>even though I have NOT decorated the Id property with a [Required] attribute</strong>.
</p>
<p>
Why does this happen? The answer is in DataAnnotationsModelValidatorProvider&#8217;s GetValidators method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>metadata.<span style="color: #0000FF;">IsRequired</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>attributes.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a <span style="color: #008000;">is</span> RequiredAttribute<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       attributes <span style="color: #008000;">=</span> attributes.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #008000;">new</span> RequiredAttribute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This checks to see if the property is a non-nullable type and it does not have a RequiredAttribute, <strong>then it assumes that the property should have a RequiredAttribute anyway!</strong><br />
You can work around this by removing the DataAnnotationsModelValidatorProvider:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
	<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
&#8230;and the test now passes.
</p>
<p>
Unfortunately, this is far from ideal. This means you cannot use the DataAnnotations attributes to validate one model and a custom provider for a different model. You have to choose one or the other.
</p>
<p>
One way to work around this problem is to use a composite validator provider that wraps the underlying providers:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CompositeValidatorProvider <span style="color: #008000;">:</span> ModelValidatorProvider <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Bootstrap<span style="color: #000000;">&#40;</span>ModelValidatorProviderCollection providerCollection, <span style="color: #0600FF;">params</span> ModelValidatorProvider<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> customProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var validators <span style="color: #008000;">=</span> customProviders.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		validators.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>providerCollection<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>validators<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">readonly</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerInnerProviders<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">protected</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">innerInnerProviders</span> <span style="color: #008000;">=</span> innerProviders<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span> GetValidators<span style="color: #000000;">&#40;</span>ModelMetadata metadata, ControllerContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var provider <span style="color: #0600FF;">in</span> innerInnerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var validators <span style="color: #008000;">=</span> provider.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>metadata, context<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>validators.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				<span style="color: #0600FF;">return</span> validators<span style="color: #008000;">;</span>	
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> Enumerable.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This custom provider can be used to wrap the built-in providers (including the DataAnnotations provider) as well as your own custom providers. In its GetValidators method, it iterates over each of the inner providers and asks each one to create a collection of validators. <strong>It only returns validators from the first provider that returns a non-empty collection</strong>. This means that if your custom provider can validate the object then the DataAnnotations provider will not be executed.</p>
<p>
Now, the following test passes:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	var fluentProvider <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	CompositeValidatorProvider.<span style="color: #0000FF;">Bootstrap</span><span style="color: #000000;">&#40;</span>ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>, fluentProvider<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This raises the question: <strong>if you have to resort to doing this, what is the point in allowing multiple validation providers to be registered in the first place?</strong>
</p>
<p>
I am really hoping that the MVC team will fix this fairly significant problem before RTM, but as MVC2 is already at the RC stage I think this will be unlikely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Controllerless Actions with ASP.NET MVC</title>
		<link>http://www.jeremyskinner.co.uk/2009/06/20/controllerless-actions-with-asp-net-mvc/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/06/20/controllerless-actions-with-asp-net-mvc/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 10:52:55 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=141</guid>
		<description><![CDATA[
There&#8217;s recently been some discussion online about the concept of using &#8216;controllerless&#8217; actions with the MVC pattern and I wanted to see how easy this would be to implement on top of ASP.NET MVC.

What is a Controllerless Action?

In a typical ASP.MVC project, a controller maps to a class and and action maps to a method [...]]]></description>
			<content:encoded><![CDATA[<p>
There&#8217;s recently been <a href="http://www.lostechies.com/blogs/chad_myers/archive/2009/06/18/going-controller-less-in-mvc-the-way-fowler-meant-it.aspx">some</a> <a href="http://jeffreypalermo.com/blog/the-asp-net-mvc-actioncontroller-ndash-the-controllerless-action-or-actionless-controller/">discussion</a> online about the concept of using &#8216;controllerless&#8217; actions with the MVC pattern and I wanted to see how easy this would be to implement on top of ASP.NET MVC.
</p>
<h2>What is a Controllerless Action?</h2>
<p>
In a typical ASP.MVC project, a controller maps to a class and and action maps to a method on that class, eg:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
&nbsp;
   <span style="color: #0600FF;">private</span> CustomerRepository customerRepository<span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> CustomerRepository<span style="color: #000000;">&#40;</span>CustomerRepository customerRepository<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">customerRepository</span> <span style="color: #008000;">=</span> customerRepository<span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> ActionResult Edit<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      var customer <span style="color: #008000;">=</span> customerRepository.<span style="color: #0000FF;">FindById</span><span style="color: #000000;">&#40;</span>id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>customer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
In this example visiting the URL <strong>/Customer/Index</strong> would invoke the <strong>Index</strong> method on the CustomerController, while </strong>/Customer/Edit/5</strong> would invoke the <strong>Edit</strong> method (with the id coming in as a parameter).
</p>
<p>
The idea behind a controllerless aciton is that each action is a separate class, so our Index action above would look like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> MyApp.<span style="color: #0000FF;">Controllers</span>.<span style="color: #0000FF;">Home</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Index <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">public</span> ActionResult Execute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
          <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> ViewResult<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h2>What are the benefits of controllerless actions?</h2>
<p>
In a small/simple project there probably isn&#8217;t much benefit. However, in a large application you&#8217;ll often find that controllers can become quite large and complex. One of the biggest problems is that different actions in the same controller class require different dependencies. For example, check out this constructor from the OrderController in <a href="http://code.google.com/p/sutekishop">SutekiShop</a>:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> OrderController<span style="color: #000000;">&#40;</span>
   IRepository<span style="color: #008000;">&lt;</span>Order<span style="color: #008000;">&gt;</span> orderRepository, 
   IRepository<span style="color: #008000;">&lt;</span>Country<span style="color: #008000;">&gt;</span> countryRepository, 
   IRepository<span style="color: #008000;">&lt;</span>CardType<span style="color: #008000;">&gt;</span> cardTypeRepository, 
   IEncryptionService encryptionService, 
   IPostageService postageService, 
   IUserService userService, 
   IOrderSearchService searchService, 
   IRepository<span style="color: #008000;">&lt;</span>OrderStatus<span style="color: #008000;">&gt;</span> statusRepository<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
   ...
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Not all of the actions in the OrderController make use of all of these dependencies. For example, the OrderSearchService is only used by the Index action. In this situation it would make sense to split the controller up into a separate class for each action. This way, each action has less baggage to carry around &#8211; it only takes dependencies on those things it actually needs. As a side effect, this helps with testability as you can test each action without having to provide stubs for the dependencies that the action doesn&#8217;t use.
</p>
<h2>ASP.NET MVC Implementation</h2>
<p>
Jeffrey Palermo has <a href="http://jeffreypalermo.com/blog/the-asp-net-mvc-actioncontroller-ndash-the-controllerless-action-or-actionless-controller/">already posted</a> an excellent example of using controllerless actions with ASP.NET MVC. In his example, you have to inherit from a class called <strong>ActionController</strong> and then create a method called <strong>Execute</strong> to handle the request. Because ActionController inherits from the existing System.Web.Mvc.Controller this allows you to make use of all the existing features in ASP.NET MVC.
</p>
<p>
However, I wanted to try something slightly different. My aim here is:
</p>
<ul>
<li>To allow action classes to be POCO (ie, not inherit from a base class)</li>
<li>To allow method invocation semantics to be configurable by using IoC container</li>
<li>To allow action filters to be configured externally (rather than using attributes)</li>
<li>To re-use as much of the ASP.NET MVC framework infrastructure as possible</li>
</ul>
<p>
I managed to succeed with most of these points, but there are some fairly major problems with this approach (see below). To start with, let&#8217;s explore the end result:
</p>
<h2>Example Application</h2>
<p>
In this example I&#8217;ll be using the <a href="http://code.google.com/p/autofac">Autofac</a> IoC container for driving the application. Code for this is example is linked to from the bottom of the post.
</p>
<p>
The first thing we need to do is configure our IoC container and register our controller factory (we also have to make our MvcApplication class implement Autofac&#8217;s IContainerProviderAccessor and set up the container disposal HTTP Module &#8211; see the sample code for the implementation):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   InitialiseContainer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #008080; font-style: italic;">//...more configuration</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> InitialiseContainer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContainerBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   builder.<span style="color: #0000FF;">RegisterModule</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ControllerlessActionsModule<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   provider <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContainerProvider<span style="color: #000000;">&#40;</span>builder.<span style="color: #0000FF;">Build</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   ServiceLocator.<span style="color: #0000FF;">SetLocatorProvider</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> provider.<span style="color: #0000FF;">RequestContainer</span>.<span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IServiceLocator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note we register a <strong>ControllerlessActionsModule</strong> with our container builder. Autofac&#8217;s modules allow you to group registrations together:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ControllerlessActionsModule <span style="color: #008000;">:</span> Module <span style="color: #000000;">&#123;</span>
   INamingConventions	namingConventions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DefaultNamingConventions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Load<span style="color: #000000;">&#40;</span>ContainerBuilder builder<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> AutofacServiceLocator<span style="color: #000000;">&#40;</span>c<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0600FF;">As</span><span style="color: #008000;">&lt;</span>IServiceLocator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ContainerScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>namingConventions<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ExternallyOwned</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> DefaultActionMethodSelector<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0600FF;">As</span><span style="color: #008000;">&lt;</span>IActionMethodSelector<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      var actionTypes <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ControllerActionLocator<span style="color: #000000;">&#40;</span>namingConventions<span style="color: #000000;">&#41;</span>
         .<span style="color: #0000FF;">FindActionsFromAssemblyContaining</span><span style="color: #008000;">&lt;</span>Index<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
         .<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0600FF;">Namespace</span>.<span style="color: #0000FF;">StartsWith</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Web.Controllers&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
         <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var action <span style="color: #0600FF;">in</span> actionTypes<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>action.<span style="color: #0000FF;">Type</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FactoryScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Named</span><span style="color: #000000;">&#40;</span>action.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
         <span style="color: #000000;">&#125;</span>
     <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here we set up our registrations with the container. Note that we are providing an implementation of INamingConventions. This is used to construct keys for the action registrations. The DefaultNamingConventions class assumes that action classes will live in a Namespace of [Application].Controllers.[Controller name]. So an &#8220;Index&#8221; action class in the &#8220;Home&#8221; namespace would be registered as &#8220;home.index.action&#8221;. We also register the <strong>DefaultActionMethodSelector</strong> (more on this below) and then use the <strong>ControllerActionLocator</strong> to find all the action classes in our assembly.
</p>
<p>
Back in our Global.asax, we also need to register the ControllerlessControllerFactory in Application_Start:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ControllerlessControllerFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> provider.<span style="color: #0000FF;">RequestContainer</span>.<span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IServiceLocator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
The ControllerlessControllerFactory asks the container to resolve our action class and then returns it for execution. Unfortunately, this is where things start to become difficult. The first problem is that the MVC Framework expects all controllers to implement the IController interface (which contains 1 method &#8211; Execute). This is a problem because we want our action classes to be POCO and have some other class responsible for their execution. To make matters worse, most of the framework expects controllers to inherit from ControllerBase (which raises the question why bother having the IController interface if you&#8217;re going to require the use of a base class?)
</p>
<p>
We can work around this problem by using a <strong>ControllerAdaptor</strong> which inherits from System.Web.Mvc.Controller and wraps our action class. The ControllerlessControllerFactory&#8217;s CreateController method looks like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> IController CreateController<span style="color: #000000;">&#40;</span>RequestContext requestContext, <span style="color: #FF0000;">string</span> controllerName<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #FF0000;">string</span> actionName <span style="color: #008000;">=</span> requestContext.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">GetRequiredString</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;action&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #FF0000;">string</span> key <span style="color: #008000;">=</span> NamingConventions.<span style="color: #0000FF;">BuildKeyFromControllerAndAction</span><span style="color: #000000;">&#40;</span>controllerName, actionName<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #FF0000;">object</span> actionInstance<span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF;">try</span> <span style="color: #000000;">&#123;</span>
      actionInstance <span style="color: #008000;">=</span>  serviceLocator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetInstance</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span><span style="color: #000000;">&#41;</span>, key<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
   <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> HttpException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">404</span>, <span style="color: #666666;">&quot;Controller not found&quot;</span>, ex<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>actionInstance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> HttpException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">404</span>, <span style="color: #666666;">&quot;Controller not found&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> ControllerAdaptor<span style="color: #000000;">&#40;</span>actionInstance, serviceLocator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The ControllerAdaptor replaces the MVC framework&#8217;s default ControllerActionInvoker with a <strong>ControllerlessActionInvoker</strong>. The ControllerlessActionInvoker calls into the implementation of <strong>IActionMethodSelector</strong> registered with our container to find the method on our action class to execute. The default behaviour is first to look for a method matching the current HTTP verb (<strong>Get</strong> or <strong>Post</strong>) or if one of these methods cannot be found then it will look for a method called <strong>Execute</strong>.
</p>
<p>
With all this wiered up, our Action class can look like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">&nbsp;
<span style="color: #0600FF;">namespace</span> Web.<span style="color: #0000FF;">Controllers</span>.<span style="color: #0000FF;">Home</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Index <span style="color: #000000;">&#123;</span>
&nbsp;
      <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">object</span> Get<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #008000;">?</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> HomeViewModel <span style="color: #000000;">&#123;</span> Id <span style="color: #008000;">=</span> id <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
&nbsp;
      <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">object</span> Post<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> name<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> ContentResult <span style="color: #000000;">&#123;</span> Content <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Hello there, &quot;</span> <span style="color: #008000;">+</span> name <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The Get method will respond to HTTP GET requests to /Home/Index and the Post method will respond to POSTs. Note that while our Post method returns a type derived from ActionResult, the Get method does not. By default in the MVC framework, if you return an object from a controller action which does not derive ActionResult then it is converted to a string and rendered to the response stream.  However, we can use an ActionFilter to apply a different convention so that if an object is returned that is *not* an ActionResult then a View will be rendered with that object as its ViewData.
</p>
<h2>Action Filter Configuration</h2>
<p>
For the most part the controllerless ActionFilter implementation re-uses the MVC Framework&#8217;s default implementation. The only difference is how we declare the filters. By default, the framework expects ActionFilters to be declared as Attributes that decorate our controller classes and action methods. I am not particularly fond of this approach as it is not suitable for use with dependency injection (although there are some workarounds &#8211; see <a href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/">here</a> and <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/12/08/attributes-are-lousy-decorators.aspx">here</a>) so I wanted to externalise the filter configuration.
</p>
<p>
The ControllerlessActions sample contains a <strong>FilterCollection</strong> class that the ControllerlessActionInvoker will use to obtain filters for the current action. This can be configured in our autofac module:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">   var filters <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FilterCollection<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>filters<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ExternallyOwned</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   builder.<span style="color: #0000FF;">RegisterTypesAssignableTo</span><span style="color: #008000;">&lt;</span>IActionFilter<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FactoryScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   builder.<span style="color: #0000FF;">RegisterTypesAssignableTo</span><span style="color: #008000;">&lt;</span>IAuthorizationFilter<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FactoryScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   filters.<span style="color: #0000FF;">Apply</span><span style="color: #008000;">&lt;</span>DecorateModelWithViewResult<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Always</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>First, we register a FilterCollection with the container and also lazily register all ActionFilters and AuthorizationFilters that are in the project. The final line says that for every action that is invoked, execute the <strong>DecorateModelWithViewResult</strong> filter. This filter looks to see if the result of an action is an object that derives from ActionResult. If not, it wraps the object in a ViewResult:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DecorateModelWithViewResult <span style="color: #008000;">:</span> IActionFilter <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> OnActionExecuted<span style="color: #000000;">&#40;</span>ActionExecutedContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      var result <span style="color: #008000;">=</span> filterContext.<span style="color: #0000FF;">Result</span> <span style="color: #0600FF;">as</span> ModelResult<span style="color: #008000;">;</span>
      <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>result <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span>.<span style="color: #0000FF;">Model</span> <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">Model</span><span style="color: #008000;">;</span>
         filterContext.<span style="color: #0000FF;">Result</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ViewResult<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
We can also configure action filters to only apply to certain actions:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">filters.<span style="color: #0000FF;">Apply</span><span style="color: #008000;">&lt;</span>AddMessageToViewData<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">When</span><span style="color: #000000;">&#40;</span>action <span style="color: #008000;">=&gt;</span> action.<span style="color: #0000FF;">ActionInstance</span> <span style="color: #008000;">is</span> Controllers.<span style="color: #0000FF;">Home</span>.<span style="color: #0000FF;">Index</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>&#8230;or alternatively&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">filters.<span style="color: #0000FF;">Apply</span><span style="color: #008000;">&lt;</span>AddMessageToViewData<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ForTypesAssignableTo</span><span style="color: #008000;">&lt;</span>Controllers.<span style="color: #0000FF;">Home</span>.<span style="color: #0000FF;">Index</span><span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h2>Limitations</h2>
<p>
Unfortunately, the MVC Framework is really designed to work with controller classes that inherit from ControllerBase. Although we can hack around this by using a ControllerAdaptor and a custom ActionInvoker the implementation is not very neat and actually ends up having to bypass some key optimizations in the framework. For example, the ControllerDescriptorCache and the ActionMethodDispatcher cache only work for the default ActionInvoker implementation, and they cannot be extended as they are marked as internal (ugh). This probably means that my solution will not perform optimally (although I haven&#8217;t run any benchmarks).</p>
<p>
I also ended up having to copy-and-paste several methods from the MVC framework source into my sample application because they were marked as private/internal.</p>
<p>
In the end, I&#8217;d tend to suggest that if you want to use controllerless actions with the ASP.NET MVC framework then you should consider using something like Jeffrey&#8217;s <a href="http://jeffreypalermo.com/blog/the-asp-net-mvc-actioncontroller-ndash-the-controllerless-action-or-actionless-controller/">ActionController base class</a> as the solution is much cleaner and simpler. Using POCO is probably a more sensible choice if you&#8217;re using a more open framework such as <a href="http://fubumvc.pbworks.com/">FubuMVC</a>
</p>
<p>
<strong>Edit:</strong> <a href="http://serialseb.blogspot.com">Seb</a> pointed out that one advantage of using POCO classes for your actions is that it makes it a lot easier to re-use them across different frameworks (eg <a href="http://trac.caffeine-it.com/openrasta">OpenRasta</a>).
</p>
<h2>Where&#8217;s the code?</h2>
<p>
All the code from this post is up on <del datetime="2009-07-20T19:49:27+00:00">my svn repository at <a href="https://www.jeremyskinner.co.uk/svn/public/trunk/ControllerlessActions">https://www.jeremyskinner.co.uk/svn/public/trunk/ControllerlessActions</a>  (username &#8216;guest&#8217;)</del> on <a href="http://github.com/JeremySkinner/Experiments/">GitHub</a> and <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/ControllerlessActions.zip">can be downloaded here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/06/20/controllerless-actions-with-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using FluentValidation with ASP.NET MVC Opinionated Input Builders</title>
		<link>http://www.jeremyskinner.co.uk/2009/06/14/using-fluentvalidation-with-asp-net-mvc-opinionated-input-builders/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/06/14/using-fluentvalidation-with-asp-net-mvc-opinionated-input-builders/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 14:27:28 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=136</guid>
		<description><![CDATA[
I&#8217;ve been following Eric Hexter&#8217;s series on using opinionated input builders with ASP.NET MVC and wanted to see whether it would be possible to use his InputBuilder code together with FluentValidation.


In Eric&#8217;s example, he has a class called SampleModel whose properties are decorated by several attributes:


public class SampleModel
&#123;
  public Guid Guid &#123; get; set; [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve been following Eric Hexter&#8217;s series on <a href="http://www.lostechies.com/blogs/hex/archive/2009/06/09/opinionated-input-builders-for-asp-net-mvc-using-partials-part-i.aspx">using opinionated input builders with ASP.NET MVC</a> and wanted to see whether it would be possible to use his InputBuilder code together with <a href="http://fluentvalidation.codeplex.com">FluentValidation</a>.
</p>
<p>
In Eric&#8217;s example, he has a class called <strong>SampleModel</strong> whose properties are decorated by several attributes:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SampleModel
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> Guid Guid <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #000000;">&#91;</span>Required<span style="color: #000000;">&#93;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #000000;">&#91;</span>Required<span style="color: #000000;">&#93;</span>
  <span style="color: #000000;">&#91;</span>Label<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Number of Types&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #000000;">&#91;</span>PartialView<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;RadioButtons&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> NumberOfTypeEnum EnumAsRadioButton <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> NumberOfTypeEnum <span style="color: #FF0000;">Enum</span> <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #000000;">&#91;</span>Range<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span>, <span style="color: #FF0000;">15</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> IntegerRangeValue <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #000000;">&#91;</span>Example<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;mm/dd/yyyy hh:mm PM&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> DateTime TimeStamp <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #000000;">&#91;</span>DataType<span style="color: #000000;">&#40;</span>DataType.<span style="color: #0000FF;">MultilineText</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Html <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> IsNeeded <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
These properties on this object are then rendered in the view by using the strongly-typed <strong>Input</strong> extension:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;%=</span>Html.<span style="color: #0000FF;">Input</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">%&gt;</span>
<span style="color: #008000;">&lt;%=</span>Html.<span style="color: #0000FF;">Input</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">TimeStamp</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">%&gt;</span>
<span style="color: #008000;">&lt;%=</span>Html.<span style="color: #0000FF;">Input</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Html</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">%&gt;</span>
...<span style="color: #0000FF;">etc</span>...</pre></div></div>

<p>The attributes that decorate the properties drive the UI, so for example decorating the Html property with [DataType(DataType.MultilineText)] would cause a multi-line textbox to be rendered.</p>
<p>
Rather than using attributes, my aim was to configure the InputBuilders by storing metadata alongside validation information in a Validator class.
</p>
<p>
Out of the box, FluentValidation supports several validator types. Some of these map nicely to the DataAnnotations attributes used by the SampleModel. For example, the [Required] attribute maps nicely to the NotNull and NotEmpty validators, and the [Range] attribute works nicely with the GreaterThan/LessThan validators:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SampleModelValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>SampleModel<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> SampleModelValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEmpty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">IntegerRangeValue</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">GreaterThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">LessThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">15</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
However, there are no equivalents for the metadata attributes such as [PartialView], [Example] or [DataType], but these can easily be built by constructing some &#8216;fake&#8217; validators (these validators won&#8217;t actually perform any validation &#8211; they will simply hold metadata).
</p>
<p>
For example, to build an equivalent for the DataTypeAttribute, we can create a property validator like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IDataTypeMetaData <span style="color: #000000;">&#123;</span>
	DataType DataType <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DataTypeValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> IPropertyValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span>, IDataTypeMetaData <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> DataType datatype<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> DataTypeValidator<span style="color: #000000;">&#40;</span>DataType datatype<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">datatype</span> <span style="color: #008000;">=</span> datatype<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> PropertyValidatorResult Validate<span style="color: #000000;">&#40;</span>PropertyValidatorContext<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> PropertyValidatorResult.<span style="color: #0000FF;">Success</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> DataType DataType <span style="color: #000000;">&#123;</span>
		get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> datatype<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that we declare both a validator to hold the DataType information and also a non-generic interface (which we&#8217;ll use later to obtain the metadata). The Validate method is a no-op, always reporting success (as we don&#8217;t actually want to perform any validation).
</p>
<p>
Next, we can declare an extension method that allows this to be used from within our SampleModelValidator:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> ValidatorExtensions <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> IRuleBuilderOptions<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> DataType<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> IRuleBuilder<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> ruleBuilder, DataType dataType<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> ruleBuilder.<span style="color: #0000FF;">SetValidator</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> DataTypeValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>dataType<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
After using this approach to create equivalents for all the other metadata attributes, our SampleModelValidator now looks like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SampleModelValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>SampleModel<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> SampleModelValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEmpty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">EnumAsRadioButton</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">RenderUsing</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;RadioButtons&quot;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">WithName</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Number of Types&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">IntegerRangeValue</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">GreaterThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">LessThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">15</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">TimeStamp</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Example</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;mm/dd/yyyy hh:mm PM&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Html</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">DataType</span><span style="color: #000000;">&#40;</span>DataType.<span style="color: #0000FF;">MultilineText</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The next stage is to create a custom <strong>ValidatorDescriptor</strong>. The default ValidatorDescriptor doesn&#8217;t do very much so we&#8217;ll need to inherit from it and create some additional methods to retrieve the information needed by the InputBuilder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">FluentValidation</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">FluentValidation.Internal</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">FluentValidation.Validators</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> ICustomValidatorDescriptor <span style="color: #000000;">&#123;</span>
	<span style="color: #FF0000;">string</span> GetExample<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #FF0000;">string</span> GetLabel<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #FF0000;">string</span> GetPartialName<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #FF0000;">bool</span> GetIsRequired<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomValidatorDescriptor<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> ValidatorDescriptor<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>, ICustomValidatorDescriptor <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> CustomValidatorDescriptor<span style="color: #000000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span>IValidationRule<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span> ruleBuilders<span style="color: #000000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF;">base</span><span style="color: #000000;">&#40;</span>ruleBuilders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetExample<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Rules.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>ISimplePropertyRule<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		       	.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Member</span> <span style="color: #008000;">==</span> prop<span style="color: #000000;">&#41;</span>
		       	.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validator</span><span style="color: #000000;">&#41;</span>
		       	.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>IExampleMetaData<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
		       	.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Example</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FirstOrDefault</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">??</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetLabel<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Rules.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>IPropertyRule<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Member</span> <span style="color: #008000;">==</span> prop<span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">PropertyDescription</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FirstOrDefault</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> GetPartialName<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Rules.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>ISimplePropertyRule<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Member</span> <span style="color: #008000;">==</span> prop<span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validator</span><span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>IRenderUsingMetaData<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
				.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">ViewName</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FirstOrDefault</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> GetIsRequired<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Rules.<span style="color: #0000FF;">OfType</span><span style="color: #008000;">&lt;</span>ISimplePropertyRule<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Member</span> <span style="color: #008000;">==</span> prop<span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validator</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x <span style="color: #008000;">is</span> INotNullValidator <span style="color: #008000;">||</span> x <span style="color: #008000;">is</span> INotEmptyValidator<span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The ValidatorDescriptor accepts in its constructor a collection of IValidationRule objects that represent the rules configured in the SampleModelValidator. Using some Linq magic we can retrieve the metadata information that we stored inside the validation rules. We also have to override the <strong>CreateDescriptor</strong> method in our SampleModelValidator to return an instance of our custom ValidatorDescriptor, rather than the default:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> IValidatorDescriptor<span style="color: #008000;">&lt;</span>SampleModel<span style="color: #008000;">&gt;</span> CreateDescriptor<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> CustomValidatorDescriptor<span style="color: #008000;">&lt;</span>SampleModel<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The next stage is to override the InputBuilder&#8217;s default conventions so that it will use our SampleModelValidator to obtain its metadata. To do this, we create a <strong>FluentValidationConventions</strong> class that accepts a ValidatorFactory in its constructor and contains methods that delegate to our CustomValidatorDescriptor:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> FluentValidationConventions <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> IValidatorFactory validatorFactory<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> FluentValidationConventions<span style="color: #000000;">&#40;</span>IValidatorFactory factory<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">validatorFactory</span> <span style="color: #008000;">=</span> factory<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">private</span> ICustomValidatorDescriptor GetDescriptor<span style="color: #000000;">&#40;</span>Type type<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var validator <span style="color: #008000;">=</span> validatorFactory.<span style="color: #0000FF;">GetValidator</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>ICustomValidatorDescriptor<span style="color: #000000;">&#41;</span> validator.<span style="color: #0000FF;">CreateDescriptor</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> ExampleConvention<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> GetDescriptor<span style="color: #000000;">&#40;</span>prop.<span style="color: #0000FF;">ReflectedType</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetExample</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> LabelConvention<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> GetDescriptor<span style="color: #000000;">&#40;</span>prop.<span style="color: #0000FF;">ReflectedType</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetLabel</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span> <span style="color: #008000;">??</span> DefaultConventions.<span style="color: #0000FF;">LabelForProperty</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> PartialNameConvention<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> GetDescriptor<span style="color: #000000;">&#40;</span>prop.<span style="color: #0000FF;">ReflectedType</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetPartialName</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span> <span style="color: #008000;">??</span> DefaultConventions.<span style="color: #0000FF;">PartialName</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> RequiredConvention<span style="color: #000000;">&#40;</span>PropertyInfo prop<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> GetDescriptor<span style="color: #000000;">&#40;</span>prop.<span style="color: #0000FF;">ReflectedType</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GetIsRequired</span><span style="color: #000000;">&#40;</span>prop<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that I used a very simple implementation of ValidatorFactory for this example that wraps a Dictionary. A real ValidatorFactory would probably wrap an IoC container or a Service Locator:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SampleValidatorFactory <span style="color: #008000;">:</span> IValidatorFactory <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">static</span> Dictionary<span style="color: #008000;">&lt;</span>Type, IValidator<span style="color: #008000;">&gt;</span> validators <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Dictionary<span style="color: #008000;">&lt;</span>Type, IValidator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #000000;">&#123;</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>SampleModel<span style="color: #000000;">&#41;</span>, <span style="color: #008000;">new</span> SampleModelValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> IValidator<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> GetValidator<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>IValidator<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span> GetValidator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span> <span style="color: #000000;">&#40;</span>T<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> IValidator GetValidator<span style="color: #000000;">&#40;</span>Type type<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		IValidator validator<span style="color: #008000;">;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>validators.<span style="color: #0000FF;">TryGetValue</span><span style="color: #000000;">&#40;</span>type, <span style="color: #0600FF;">out</span> validator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">return</span> validator<span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
In our global.asax, we can then replace the InputBuilder&#8217;s default conventions with our custom conventions:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	InputBuilder.<span style="color: #0000FF;">InputBuilder</span>.<span style="color: #0000FF;">BootStrap</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	SetupFluentValidationConventions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> SetupFluentValidationConventions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var conventions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationConventions<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> SampleValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ModelPropertyFactory.<span style="color: #0000FF;">ExampleForPropertyConvention</span> <span style="color: #008000;">=</span> conventions.<span style="color: #0000FF;">ExampleConvention</span><span style="color: #008000;">;</span>
	ModelPropertyFactory.<span style="color: #0000FF;">LabelForPropertyConvention</span> <span style="color: #008000;">=</span> conventions.<span style="color: #0000FF;">LabelConvention</span><span style="color: #008000;">;</span>
	ModelPropertyFactory.<span style="color: #0000FF;">PartialNameConvention</span> <span style="color: #008000;">=</span> conventions.<span style="color: #0000FF;">PartialNameConvention</span><span style="color: #008000;">;</span> 
	ModelPropertyFactory.<span style="color: #0000FF;">PropertyIsRequiredConvention</span> <span style="color: #008000;">=</span> conventions.<span style="color: #0000FF;">RequiredConvention</span><span style="color: #008000;">;</span> 
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and that&#8217;s it. The InputBuilder will now get all its metadata from our Validator class rather than from attributes. If you want to play with the source code for this example it&#8217;s available <del datetime="2009-07-20T19:53:40+00:00">in my svn repository at <strong>https://www.jeremyskinner.co.uk/svn/public/trunk/FluentValidationInputBuilders</strong> (username &#8216;guest&#8217;)</del> on <a href="http://github.com/JeremySkinner/Experiments/tree/master">GitHub</a> and can be <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/FluentValidationInputBuilders.zip">downloaded from here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/06/14/using-fluentvalidation-with-asp-net-mvc-opinionated-input-builders/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using ModelState with MvcContrib&#8217;s Fluent HTML Helpers</title>
		<link>http://www.jeremyskinner.co.uk/2008/12/18/using-modelstate-with-mvccontribs-fluent-html-helpers/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/12/18/using-modelstate-with-mvccontribs-fluent-html-helpers/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 12:11:04 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=71</guid>
		<description><![CDATA[What is ModelState?

The ASP.NET MVC ModelState dictionary allows you to record validation errors which can then be displayed in your web page.

For example, imagine you add a textbox to a page using the MVC framework&#8217;s built-in HTML helpers, then this will render a standard text field:


Your name: &#60;%= Html.TextBox&#40;&#34;Name&#34;&#41; %&#62;

In your controller, if you add [...]]]></description>
			<content:encoded><![CDATA[<h3>What is ModelState?</h3>
<p>
The ASP.NET MVC ModelState dictionary allows you to record validation errors which can then be displayed in your web page.
</p>
<p>For example, imagine you add a textbox to a page using the MVC framework&#8217;s built-in HTML helpers, then this will render a standard text field:
</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;">Your name: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBox</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;Name&quot;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

<p>In your controller, if you add an error to the ModelState dictionary with the same name as the textbox, then the HTML helper will change the styling of the input field by adding a css class of &#8220;input-validation-error&#8221;. </p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> HomeController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       ModelState.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Name&quot;</span>, <span style="color: #666666;">&quot;Please enter a name&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
       <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> MyViewModel <span style="color: #000000;">&#123;</span> Name <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Using the default ASP.NET MVC template, it will add a red border with a light pink background:</p>
<p><img src="/files/textbox-error.png" alt="Textbox error" style="border:1px solid #bebebe" /></p>
<p>
You can also display the actual validation errors by making use of the ValidationSummary helper:
</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationSummary</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
Enter your name: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBox</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #cc0000;">&quot;Name&quot;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

<p>Which will display something like this:</p>
<p><img src="/files/textbox-validationsummary.png" style="border:1px solid #bebebe" alt="Validation Summary" /></p>
<h3>ModelState with FluentHtml</h3>
<p>
By default, the Fluent HTML helpers in MvcContrib do not have support for ModelState. However, it is very easy to add support for this by writing a custom MemberBehaviour (I previously wrote about extending the HTML helpers with MemberBehaviors  <a href="http://www.jeremyskinner.co.uk/2008/12/13/integrating-fluentvalidation-with-mvccontribs-fluent-html-helpers/">here</a>)
</p>
<p>
Here is the implementation of the ModelStateMemberBehavior class:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ModelStateMemberBehavior <span style="color: #008000;">:</span> IMemberBehavior <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> ModelStateDictionary modelState<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ModelStateMemberBehavior<span style="color: #000000;">&#40;</span>ModelStateDictionary modelState<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">modelState</span> <span style="color: #008000;">=</span> modelState<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Execute<span style="color: #000000;">&#40;</span>IMemberElement element<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		ModelState state<span style="color: #008000;">;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>element.<span style="color: #0000FF;">Builder</span>.<span style="color: #0000FF;">Attributes</span>.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;name&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>modelState.<span style="color: #0000FF;">TryGetValue</span><span style="color: #000000;">&#40;</span>element.<span style="color: #0000FF;">Builder</span>.<span style="color: #0000FF;">Attributes</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;name&quot;</span><span style="color: #000000;">&#93;</span>, <span style="color: #0600FF;">out</span> state<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				element.<span style="color: #0000FF;">Builder</span>.<span style="color: #0000FF;">AddCssClass</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;input-validation-error&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This class will check whether the name of the element being rendered is present in the specified ModelState dictionary. If so, it will add a css class of &#8220;input-validation-error&#8221; to the element being rendered.</p>
<p>
Now we need to hook this into the HTML helpers. This can be done by implementing the IViewModelContainer interface on your base View Page:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyBaseViewPage<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> ViewPage<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span>, IViewModelContainer<span style="color: #008000;">&lt;</span>T<span style="color: #008000;">&gt;</span> where T <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">private</span> List<span style="color: #008000;">&lt;</span>IMemberBehavior<span style="color: #008000;">&gt;</span> memberBehaviors <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>IMemberBehavior<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
   <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> SetViewData<span style="color: #000000;">&#40;</span>ViewDataDictionary viewData<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">base</span>.<span style="color: #0000FF;">SetViewData</span><span style="color: #000000;">&#40;</span>viewData<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      behaviors.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ModelStateMemberBehavior<span style="color: #000000;">&#40;</span>ViewData.<span style="color: #0000FF;">ModelState</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> T ViewModel <span style="color: #000000;">&#123;</span>
      get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> ViewData.<span style="color: #0000FF;">Model</span><span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
   <span style="color: #000000;">&#125;</span>
&nbsp;
   <span style="color: #0600FF;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>IMemberBehavior<span style="color: #008000;">&gt;</span> MemberBehaviors <span style="color: #000000;">&#123;</span>
	get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> memberBehaviors<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, so long as all your view pages inherit from MyBaseViewPage<T>, any calls to the fluent HTML helpers will have support for ModelState:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;">Your name: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> this.<span style="color: #9900cc;">TextBox</span><span style="color: #006600; font-weight:bold;">&#40;</span>model <span style="color: #006600; font-weight: bold;">=&gt;</span> model.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/12/18/using-modelstate-with-mvccontribs-fluent-html-helpers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dependency Injection with ASP.NET MVC Action Filters</title>
		<link>http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/#comments</comments>
		<pubDate>Sat, 08 Nov 2008 18:59:49 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[aspnetmvc]]></category>
		<category><![CDATA[autofac]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=52</guid>
		<description><![CDATA[Action Filter attributes in ASP.NET MVC are a very nice way of encapsulating logic into small reusable components that can easily be reused across multiple controllers.
However, if you need your action filters to do anything complex, injecting services into action filters using an Inversion of Control container (such as Windsor or StructureMap) can be painful. [...]]]></description>
			<content:encoded><![CDATA[<p>Action Filter attributes in ASP.NET MVC are a very nice way of encapsulating logic into small reusable components that can easily be reused across multiple controllers.</p>
<p>However, if you need your action filters to do anything complex, injecting services into action filters using an <a href="http://martinfowler.com/articles/injection.html">Inversion of Control container</a> (such as <a href="http://castleproject.org/container/index.html">Windsor</a> or <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a>) can be painful. </p>
<p>Typically, when using an IoC container it is necessary to register all your components with the container up-front and then use the container to create instances for you. When the container creates the object, it will also create any required dependencies and pass them to the constructor (or property setters).</p>
<p>However, as ActionFilters are defined as attributes, they cannot be instantiated by the container. One solution to this problem is to wrap the container with a static class and then make use of constructor chaining to create the illusion of automatic dependency resolution:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LoggingFilter <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> ILogger logger<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> LoggingFilter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF;">this</span><span style="color: #000000;">&#40;</span>IoC.<span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>ILogger<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> LoggingFilter<span style="color: #000000;">&#40;</span>ILogger logger<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">logger</span> <span style="color: #008000;">=</span> logger<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    logger.<span style="color: #0000FF;">log</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Entering action: &quot;</span> <span style="color: #008000;">+</span> context.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">GetRequiredString</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;action&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>In this example, the default constructor will call into a static &#8216;IoC&#8217; class (which wraps the underlying container) to resolve an ILogger instance and then pass this to the second constructor. In a unit-testing scenario, you can make use of the second constructor directly in order to supply a mocked ILogger instance.</p>
<p>There are several things I don&#8217;t like about this code:</p>
<ol>
<li>The filter now has a coupling to the container</li>
<li>If you trigger the instantiation of the attribute without first initialising the container then this can lead to problems (eg reflecting over a method&#8217;s attributes in a unit-testing scenario)</li>
<li>It&#8217;s just plain ugly!</li>
</ol>
<p>Thankfully, there is a better way. Several IoC containers (including <a href="http://code.google.com/p/autofac">Autofac</a> and <a href="http://codeplex.com/unity">Unity</a>) can inject services into objects using property setters <strong>without the target object needing to be registered with the container.</strong> I&#8217;ll be using Autofac for the sample code.</p>
<p>
We can write a custom ControllerActionInvoker to make use of this feature by intercepting the action filters before they are invoked. The custom action invoker looks like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">namespace</span> MyApp <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Web.Mvc</span><span style="color: #008000;">;</span>
  <span style="color: #0600FF;">using</span> <span style="color: #008080;">Autofac</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyActionInvoker <span style="color: #008000;">:</span> ControllerActionInvoker <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> IContainer container<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> MyActionInvoker<span style="color: #000000;">&#40;</span>IContainer container<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">container</span> <span style="color: #008000;">=</span> container<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> ActionExecutedContext InvokeActionMethodWithFilters<span style="color: #000000;">&#40;</span>MethodInfo methodInfo, IDictionary<span style="color: #008000;">&lt;</span><span style="color: #FF0000;">string</span>, <span style="color: #FF0000;">object</span><span style="color: #008000;">&gt;</span> parameters, IList<span style="color: #008000;">&lt;</span>IActionFilter<span style="color: #008000;">&gt;</span> filters<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>var filter <span style="color: #0600FF;">in</span> filters<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        container.<span style="color: #0000FF;">InjectProperties</span><span style="color: #000000;">&#40;</span>filter<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      <span style="color: #000000;">&#125;</span>
      <span style="color: #0600FF;">return</span> <span style="color: #0600FF;">base</span>.<span style="color: #0000FF;">InvokeActionMethodWithFilters</span><span style="color: #000000;">&#40;</span>methodInfo, parameters, filters<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The custom action invoker takes an instance of IContainer (the autofac container) in its constructor, which it can then use to inject services into the action filter attributes before they are invoked. This is done by overriding the <strong>InvokeActionMethodWithFilters</strong> method and calling <strong>container.InjectProperties</strong> for each object in the filters collection.</p>
<p>
In order to get Autofac working with ASP.NET MVC, you need to register an HTTP module as well as set up the AutofacControllerFactory (<a href="http://code.google.com/p/autofac/wiki/MvcIntegration">instructions here</a>.)
</p>
<p>
It is also necessary to register the custom action invoker with Autofac in your global.asax:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ContainerBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
builder.<span style="color: #0000FF;">Register</span><span style="color: #008000;">&lt;</span>MyActionInvoker<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0600FF;">As</span><span style="color: #008000;">&lt;</span>IActionInvoker<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">FactoryScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
As well as the ActionInvoker, you also need to register your controllers. Autofac contains a &#8216;module&#8217; for doing this (the <a href="http://autofac.googlecode.com/svn/trunk/src/Source/Autofac.Integration.Web.Mvc/AutofacControllerModule.cs">AutofacControllerModule</a>), but we need to make a slight modification in order to use our custom action invoker. The modified module looks like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ControllerModule <span style="color: #008000;">:</span> Module <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> Assembly assembly<span style="color: #008000;">;</span>
  <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> IControllerIdentificationStrategy controllerNamingStrategy <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DefaultControllerIdentificationStrategy<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> ControllerModule<span style="color: #000000;">&#40;</span>Assembly assembly<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">assembly</span> <span style="color: #008000;">=</span> assembly<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> Load<span style="color: #000000;">&#40;</span>ContainerBuilder builder<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var controllers <span style="color: #008000;">=</span> from type <span style="color: #0600FF;">in</span> assembly.<span style="color: #0000FF;">GetExportedTypes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
                           where <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>IController<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span> 
			   where <span style="color: #008000;">!</span>type.<span style="color: #0000FF;">IsAbstract</span>
		           select type<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>var type <span style="color: #0600FF;">in</span> controllers<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      builder.<span style="color: #0000FF;">Register</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">FactoryScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0600FF;">As</span><span style="color: #000000;">&#40;</span>controllerNamingStrategy.<span style="color: #0000FF;">ServiceForControllerType</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
        .<span style="color: #0600FF;">As</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span>
        .<span style="color: #0000FF;">OnActivating</span><span style="color: #000000;">&#40;</span>InjectInvoker<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> InjectInvoker<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, ActivatingEventArgs e<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>Controller<span style="color: #000000;">&#41;</span>e.<span style="color: #0000FF;">Instance</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ActionInvoker</span> <span style="color: #008000;">=</span> e.<span style="color: #0000FF;">Context</span>.<span style="color: #0000FF;">Resolve</span><span style="color: #008000;">&lt;</span>IActionInvoker<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now when a controller is instantiated, the ActionInvoker property will be set to an instance of our custom action invoker. The module should be registered with the container builder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">builder.<span style="color: #0000FF;">RegisterModule</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> ControllerModule<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>HomeController<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Assembly</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>So, assuming an ILogger instance is registered with the container, the sample LoggingFilter could be written like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LoggingFilter <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> ILogger Logger <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    Logger.<span style="color: #0000FF;">log</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Entering action: &quot;</span> <span style="color: #008000;">+</span> context.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">GetRequiredString</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;action&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Much better!</p>
<p>
The same approach can also be used for other filter types, (such as AuthorizationFilters) by overriding the appropriate method.
</p>
<p>Note that container.InjectProperties makes use of reflection, so there is a potetial performance issue here.</p>
<p>
<strong>Edit (5 December 2008):</strong> Here is an extension method that adds the InjectProperties method to the Microkernel from Castle Windsor.
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Castle.MicroKernel</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Castle.MicroKernel.ComponentActivator</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> WindsorExtension <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> InjectProperties<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> IKernel kernel, <span style="color: #FF0000;">object</span> target<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var type <span style="color: #008000;">=</span> target.<span style="color: #0000FF;">GetType</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var property <span style="color: #0600FF;">in</span> type.<span style="color: #0000FF;">GetProperties</span><span style="color: #000000;">&#40;</span>BindingFlags.<span style="color: #0600FF;">Public</span> <span style="color: #008000;">|</span> BindingFlags.<span style="color: #0000FF;">Instance</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>property.<span style="color: #0000FF;">CanWrite</span> <span style="color: #008000;">&amp;&amp;</span>  kernel.<span style="color: #0000FF;">HasComponent</span><span style="color: #000000;">&#40;</span>property.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				var value <span style="color: #008000;">=</span> kernel.<span style="color: #0000FF;">Resolve</span><span style="color: #000000;">&#40;</span>property.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
				<span style="color: #0600FF;">try</span> <span style="color: #000000;">&#123;</span>
					property.<span style="color: #0000FF;">SetValue</span><span style="color: #000000;">&#40;</span>target, value, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
				<span style="color: #000000;">&#125;</span>
				<span style="color: #0600FF;">catch</span><span style="color: #000000;">&#40;</span>Exception ex<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
					var message <span style="color: #008000;">=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Error setting property {0} on type {1}, See inner exception for more information.&quot;</span>, property.<span style="color: #0000FF;">Name</span>, type.<span style="color: #0000FF;">FullName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
					<span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> ComponentActivatorException<span style="color: #000000;">&#40;</span>message, ex<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
				<span style="color: #000000;">&#125;</span>
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Storing ModelState in TempData with ASP.NET MVC</title>
		<link>http://www.jeremyskinner.co.uk/2008/10/18/storing-modelstate-in-tempdata-with-aspnet-mvc/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/10/18/storing-modelstate-in-tempdata-with-aspnet-mvc/#comments</comments>
		<pubDate>Sat, 18 Oct 2008 15:19:15 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=44</guid>
		<description><![CDATA[
MVC Preview 5 introduced the contept of ModelState for storing validation failures.


As the ModelState is part of the ViewData, it is only available for the current request. This means that you cannot redirect to another action in order to show the error summary, instead you have to render a view directly from your Save action. [...]]]></description>
			<content:encoded><![CDATA[<p>
MVC Preview 5 <a href="http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx">introduced the contept of ModelState</a> for storing validation failures.
</p>
<p>
As the ModelState is part of the ViewData, it is only available for the current request. This means that you cannot redirect to another action in order to show the error summary, instead you have to render a view directly from your <em>Save</em> action. Personally I don&#8217;t think this is a good idea &#8211; the Save action should just try and save changes, and then redirect to another action to display validation errors.
</p>
<p>
One solution is to store the ModelState inside the TempData (as anything added to the TempData will be made available to the next HTTP request). It is possible to use an ActionFilterAttribute to make this happen automatically.
</p>
<p>
Under the covers, TempData makes use of ASP.NET Session State which means that every object that is stored in TempData needs to be marked as Serializable if you are using an out of process session store. Unfortunately, the ModelStateDictionary is not marked as serializable, so in order for this approach to work it is necessary to copy the contents of the ModelState into a temporary serializable dictionary.
</p>
<p>
I&#8217;ve made the code <a href="http://mvccontrib.googlecode.com/svn/trunk/src/MVCContrib/Filters/ModelStateToTempDataAttribute.cs">available in MvcContrib</a>. You can use it by decorating your controllers with the ModelStateToTempData attribute:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">MvcContrib.Filters</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>ModelStateToTempData<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
  <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The filter has the following features:</p>
<ul>
<li>If your controller action returns a RedirectToRouteResult, anything in the ModelState dictionary will be wrapped in a ModelStateSerializable class and stored in TempData.</li>
<li>If your action returns a ViewResult, then any ModelState objects that were previously copied to TempData will be re-added to the ModelState dictionary.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/10/18/storing-modelstate-in-tempdata-with-aspnet-mvc/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>HandleErrorAttribute and Remote Connections</title>
		<link>http://www.jeremyskinner.co.uk/2008/07/23/handleerrorattribute-and-remote-connections/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/07/23/handleerrorattribute-and-remote-connections/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 08:15:20 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=39</guid>
		<description><![CDATA[Last week I upgraded my main application to MVC Preview 4. This morning I noticed that a number of users were receiving HTTP 500 error messages instead of being presented with a friendly error page. 
It turns out the HandleErrorAttribute in Preview 4 is the culprit. Previously I&#8217;d been using MvcContrib&#8217;s RescueAttribute. 

It appears that [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I upgraded my main application to MVC Preview 4. This morning I noticed that a number of users were receiving HTTP 500 error messages instead of being presented with a friendly error page. </p>
<p>It turns out the HandleErrorAttribute in Preview 4 is the culprit. Previously I&#8217;d been using MvcContrib&#8217;s <a href="http://www.codeplex.com/MVCContrib/Wiki/View.aspx?title=Rescue&#038;referringTitle=Documentation">RescueAttribute</a>. </p>
<p>
It appears that the HandleError attribute only works locally &#8211; when using a remote connection the server just displays the standard HTTP 500 message (this is under IIS7 using Integrated Pipeline).
</p>
<p>
I fired up the MVC source code and removed this line from HandleErrorAttribute.cs (line 85):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">Response</span>.<span style="color: #0000FF;">StatusCode</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">500</span><span style="color: #008000;">;</span></pre></div></div>

<p>After doing this, the error pages are displayed correctly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/07/23/handleerrorattribute-and-remote-connections/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC Preview 4</title>
		<link>http://www.jeremyskinner.co.uk/2008/07/18/aspnet-mvc-preview-4/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/07/18/aspnet-mvc-preview-4/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 13:47:53 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=38</guid>
		<description><![CDATA[I spent yesterday updating our largest application to MVC Preview 4. As part of the upgrade, I also made some tweaks to MvcContrib&#8217;s ConventionController (documentation not yet updated).
Here&#8217;s a summary of some of the things that have changed:

TempData finally works with out of process session state
Filters that implement IExceptionFilter can easily catch exceptions thrown by [...]]]></description>
			<content:encoded><![CDATA[<p>I spent yesterday updating our largest application to MVC Preview 4. As part of the upgrade, I also made some tweaks to MvcContrib&#8217;s <a href="http://www.codeplex.com/MVCContrib/Wiki/View.aspx?title=ConventionController&#038;referringTitle=Documentation">ConventionController</a> (documentation not yet updated).</p>
<p>Here&#8217;s a summary of some of the things that have changed:</p>
<ul>
<li>TempData finally works with out of process session state</li>
<li>Filters that implement IExceptionFilter can easily catch exceptions thrown by other filters</li>
<li>The RescueAttribute in MvcContrib is now an IExceptionFilter, so it can be used with classes that don&#8217;t inherit from ConventionController</li>
<li>Multiple filters can now have the same sort order. This makes it easy to define a &#8216;default&#8217; order, and then have other filters execute before/after</li>
<li>TempData is now testable without needing to mock anything</li>
<li>All the ComponentController hackery is gone &#8211; RenderAction is a much nicer alternative</li>
<li>The <a href="http://www.jeremyskinner.co.uk/2008/06/03/aspnet-mvc-intercepting-the-routevaluedictionary/">bug that broke URL generation</a> is fixed</li>
</ul>
<p>Here&#8217;s what sucks with Preview 4:</p>
<ul>
<li>SubDataItems <a href="http://blog.eworldui.net/post/2008/06/Using-SubDataItems-and-View-User-Controls-in-ASPNET-MVC.aspx">still doesn&#8217;t seem to work properly</a></li>
<li>AuthorizeAttribute, OutputCacheAttribute and HandleError attribute are sealed and have no virtual methods</li>
<li>The new built in Ajax support doesn&#8217;t seem to be easily replaceable with alternative libraries</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/07/18/aspnet-mvc-preview-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC &#8211; Intercepting the RouteValueDictionary</title>
		<link>http://www.jeremyskinner.co.uk/2008/06/03/aspnet-mvc-intercepting-the-routevaluedictionary/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/06/03/aspnet-mvc-intercepting-the-routevaluedictionary/#comments</comments>
		<pubDate>Tue, 03 Jun 2008 08:02:52 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://jeremyskinner.wordpress.com/?p=33</guid>
		<description><![CDATA[ASP.NET MVC Preview 3 suffers from a bug where the controller name is omitted from the RouteValueDictionary when you call Html.ActionLink or Url.Action unless you explicitly specify it. 
Imagine you have the following routes defined:

routes.Add&#40;new Route&#40;&#34;Other/List&#34;,
	new RouteValueDictionary&#40;new &#123;
		controller = &#34;Other&#34;,
		action = &#34;List&#34;
	&#125;&#41;,
	new MvcRouteHandler&#40;&#41;&#41;
&#41;;
&#160;
routes.Add&#40;new Route&#40;&#34;{controller}/{action}/{id}&#34;,
	new RouteValueDictionary&#40;new &#123;
		action = &#34;Index&#34;,
		id = &#40;string&#41;null
	&#125;&#41;,
	new MvcRouteHandler&#40;&#41;&#41;
&#41;;

..and you have a HomeController [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.NET MVC Preview 3 suffers from a bug where the controller name is omitted from the RouteValueDictionary when you call Html.ActionLink or Url.Action unless you explicitly specify it. </p>
<p>Imagine you have the following routes defined:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Route<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Other/List&quot;</span>,
	<span style="color: #008000;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span>
		controller <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Other&quot;</span>,
		action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;List&quot;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>,
	<span style="color: #008000;">new</span> MvcRouteHandler<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Route<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{controller}/{action}/{id}&quot;</span>,
	<span style="color: #008000;">new</span> RouteValueDictionary<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span>
		action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Index&quot;</span>,
		id <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#41;</span><span style="color: #0600FF;">null</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>,
	<span style="color: #008000;">new</span> MvcRouteHandler<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>..and you have a HomeController with two actions: Index and List</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> HomeController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> ActionResult Index<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult List<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
And imagine the following code in the Index view:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;%=</span> Url.<span style="color: #0000FF;">Action</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;List&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">%&gt;</span></pre></div></div>

<p>This should generate <b>MyApp/Home/List</b> but instead it generates <b>MyApp/Other/List</b>. </p>
<p>To work around this, you can intercept the RouteValueDictionary before it is passed to your routes by adding a route &#8216;pre-parser&#8217;. In here, you can copy the controller name from the routedata into the RouteValuesDictionary.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> RouteValuePreParser <span style="color: #008000;">:</span> RouteBase <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> RouteData GetRouteData<span style="color: #000000;">&#40;</span>HttpContextBase httpContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> VirtualPathData GetVirtualPath<span style="color: #000000;">&#40;</span>RequestContext requestContext, RouteValueDictionary values<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>values.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;controller&quot;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> requestContext.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">Values</span>.<span style="color: #0000FF;">ContainsKey</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;controller&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			values.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;controller&quot;</span>, requestContext.<span style="color: #0000FF;">RouteData</span>.<span style="color: #0000FF;">Values</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;controller&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>You can then add this &#8216;fake&#8217; route to your RouteTable, but it must be the <b>first</b> route:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RouteTable.<span style="color: #0000FF;">Routes</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> RouteValuePreParser<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/06/03/aspnet-mvc-intercepting-the-routevaluedictionary/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MvcContrib upgraded to ASP.NET MVC Preview 3</title>
		<link>http://www.jeremyskinner.co.uk/2008/05/30/mvccontrib-upgraded-to-aspnet-mvc-preview-3/</link>
		<comments>http://www.jeremyskinner.co.uk/2008/05/30/mvccontrib-upgraded-to-aspnet-mvc-preview-3/#comments</comments>
		<pubDate>Fri, 30 May 2008 16:31:00 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[mvccontrib]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://jeremyskinner.wordpress.com/?p=32</guid>
		<description><![CDATA[I&#8217;ve just finished upgrading MvcContrib to work with ASP.NET MVC Preview 3.
The source can be downloaded from http://mvccontrib.googlecode.com/svn/trunk/ using your favourite Subversion client.
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just finished upgrading <a href="http://mvccontrib.org">MvcContrib</a> to work with <a href="http://weblogs.asp.net/scottgu/archive/2008/05/27/asp-net-mvc-preview-3-release.aspx">ASP.NET MVC Preview 3.</a></p>
<p>The source can be downloaded from <strong>http://mvccontrib.googlecode.com/svn/trunk/</strong> using your favourite Subversion client.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2008/05/30/mvccontrib-upgraded-to-aspnet-mvc-preview-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
