<?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>Darren Cauthon &#187; Blog</title>
	<atom:link href="http://www.cauthon.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cauthon.com</link>
	<description></description>
	<lastBuildDate>Thu, 03 Jun 2010 12:14:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>MvcTurbine.Laziness, and Leveraging a CSL</title>
		<link>http://www.cauthon.com/2010/06/03/mvcturbine-laziness-and-leveraging-a-csl/</link>
		<comments>http://www.cauthon.com/2010/06/03/mvcturbine-laziness-and-leveraging-a-csl/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 12:11:22 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[aspnetmvc]]></category>
		<category><![CDATA[lazy]]></category>
		<category><![CDATA[mvcturbine]]></category>

		<guid isPermaLink="false">http://www.cauthon.com/?p=851</guid>
		<description><![CDATA[MvcTurbineLazy-loading, or waiting to instantiate your object or execute a query until the very moment where it&#8217;s required, is pretty important for a well-performing application.  By waiting until the last possible moment to execute a command, you give yourself the freedom to alter, limit, or eliminate all-together code that would have otherwise been executed. This [...]]]></description>
			<content:encoded><![CDATA[<p>MvcTurbineLazy-loading, or waiting to instantiate your object or execute a query until the very moment where it&#8217;s required, is pretty important for a well-performing application.  By waiting until the last possible moment to execute a command, you give yourself the freedom to alter, limit, or eliminate all-together code that would have otherwise been executed.</p>
<p>This goes double for applications built on SOLID principles, especially the Single Responsibility Principle and Dependency Inversion Principle.  These types of applications tend to have many small classes that do one thing and that are isolated from the code in other classes.  It&#8217;s very possible for one class to return results and another class determine whether those results are necessary.  It&#8217;s also possible for a class to have a dependency on another class that is expensive to instantiate.  Without an idea like lazy-loading, these situations could force you to couple bits of code that would normally be kept apart.</p>
<p>I was in one of these situations recently in an ASP.Net MVC application with MVC Turbine.  I had a route with a route constraint that had a dependency on a repository.  If a specific part of the URL matched an item in the repository, the route was considered valid.  The issue I had was that the routes were being built before my caching &#8220;blade&#8221; was run, so the route constraint was instantiated with a repository tied to my database instead of a repository tied to the cache.  What should I do?  Bring in my IoC container as a dependency to the route constraint?  Should I alter MVC Turbine to make my caching blade to run before the routing blade?  Should I write a special lazy loader for this situation?</p>
<p>In every time I&#8217;ve been in this situation, I&#8217;ve gone with the last option.  It&#8217;s pretty easy:</p>
<pre lang="C#">public class RepositoryLazyLoader {

   private IServiceLocator locator;

   public RepositoryLazyLoader(IServiceLocator locator){
      this.locator = locator;
   }

   public IRepository GetRepository() {
      return locator.Resolve&lt;IRepository&gt;();
   }

}</pre>
<p>This lazy loader is basically a wrapper around my IoC container.  It seems like I&#8217;ve had to write one or two of these in every project, so I had an idea:  Why not write this one more time and never write it again?</p>
<p><strong>MvcTurbine.Laziness</strong></p>
<p>Since I use MVC Turbine on every ASP.Net MVC application I write, I decided to write a &#8220;blade&#8221; (which is essentially a module you can plug into your MVC app) that would handle creating lazy loaders.  Instead of writing a lazy loader when I need one, I can just instantiate an ILazy&lt;T&gt; from my IoC container.  The ILazy&lt;T&gt; has one property, Value, that will return the value from the IoC container.  The value will *not* be instantiated until then, so I can change a constructor like this:</p>
<pre lang="C#">public SuperConstraint(IRepository repository) { // IRepository will be instantiated right NOW</pre>
<p>to:</p>
<pre lang="C#">public SuperConstraint(ILazy&lt;IRepository&gt; lazyRepository) { // IRepository will be instantiated LATER</pre>
<p>In order to use this, here&#8217;s what you have to do:</p>
<p>1.)  Use MVC Turbine.<br />
1.)  Add a reference to MvcTurbine.Laziness.dll .<br />
2.)  Add a reference to MvcTurbine.Laziness.X.dll, where X is either Unity, StructureMap, Ninject, or Windsor.</p>
<p>That&#8217;s all.  Just by adding references to these dlls, MVC Turbine will suck them into the application startup and add a registration for ILazy&lt;&gt; to your IoC.  The only work I&#8217;ve done is to figure out how to register ILazy&lt;&gt; into each of those containers (which can be seen here for <a href="http://github.com/darrencauthon/MvcTurbine.Laziness/blob/15a39341036f7ffa8ba23839813e0e676289c59d/src/MvcTurbine.Laziness.Unity/UnityLazySetup.cs">Unity</a>,<a href="http://github.com/darrencauthon/MvcTurbine.Laziness/blob/master/src/MvcTurbine.Laziness.StructureMap/StructureMapLazySetup.cs">StructureMap</a>, <a href="http://github.com/darrencauthon/MvcTurbine.Laziness/blob/6fb0b5ed7d97fc4d7d0d52bf16e5a8d0ec2e72e0/src/MvcTurbine.Laziness.Ninject/NinjectLazySetup.cs">Ninject</a>, or <a href="http://github.com/darrencauthon/MvcTurbine.Laziness/blob/15a39341036f7ffa8ba23839813e0e676289c59d/src/MvcTurbine.Laziness.Windsor/WindsorLazySetup.cs">Windsor</a>).  Not much there.</p>
<p><strong>Leveraging a CSL</strong></p>
<p>MVC Turbine comes with a common service locator that serves as an abstraction on top of all of the IoC containers.  It&#8217;s similar to the <a href="http://commonservicelocator.codeplex.com/" target="_blank">Common Service Locator</a> you can find on Codeplex, except that MVC Turbine adds the ability to register mappings as well as resolve them.  If you stick with the standard features that MVC Turbine&#8217;s service provider offers, you can actually swap your IoC container without any impact on your MVC application.  Let me repeat that:  <strong>You can swap your IoC container without any impact on your MVC application. </strong>So with one line of code, you can swap Unity with StructureMap, or StructureMap with Unity, or with Ninject, or with Castle Windsor.  Wow, right?</p>
<p>&#8220;Big deal,&#8221; you say?  You know how to use your IoC-container-of-choice and you&#8217;ll never want to switch?  That&#8217;s how I felt a while ago.  I cut my DI teeth on Unity.  I know it.  I know how to handle configuration, lifetime management, interception, or anything else I could imagine wanting out of an IoC container.  All of my projects had direct references to Unity, everything worked, and I thought I was cool.  Then I hit an issue or two with Unity, including a memory leak in the disposal of child containers.  The issues were all worked out in time, but when I was in the middle of them it was pretty scary.  I wrote a huge application that was glued to my IoC container, to the point where I was literally stuck with it.  What if the issues couldn&#8217;t get worked out?  What if I *had* to replace Unity?  I could do it, but it definitely wouldn&#8217;t be a one-line change.</p>
<p>&#8220;But Unity is stinky and my IoC container issue works just fine, I&#8217;ll never have to swap it out.&#8221;  That&#8217;s great, but I think it&#8217;s still a bad practice to tie any third-party library directly into your application.  Your classes should depend on abstractions, not implementations, and this is true even with the class that&#8217;s responsible for mapping your abstractions to your implementations.  I&#8217;ve found, through much experience and pain, that when you tie yourself to anybody else, you&#8217;ll go down with them.  Adding one simple layer of abstraction will protect you and will keep your code focused on what you want instead of what they give you.  That&#8217;s what a CSL like the that comes with MVC Turbine will provide you.</p>
<p>Think about it this way:  I wanted to provide this ILazy&lt;T&gt; feature in my application.  If I were touching my IoC container directly, this is the point where I&#8217;d sink even deeper into it.  I&#8217;d write code that could only work with my IoC container, making yet another dependency on a third-party.  The next feature I write will probably be the same, as will the next.  I&#8217;m definitely on the wrong path.  But if I write a solution that&#8217;s meant to be IoC-agnostic, I&#8217;m covered and I&#8217;m on the right path.</p>
<p>If you want a better example of this, look at the MVC Turbine framework itself.  It lets you inject IoC into your ASP.NET MVC and MVC2 app, yet it doesn&#8217;t tie you to a specific IoC container.  This makes it possible to add this ILazy&lt;T&gt; feature, a <a href="http://www.cauthon.com/2010/05/24/mvcturbine-fluentvalidation/" target="_self">Fluent Validation plugin</a>, or any number of things (I&#8217;m working on some new ideas) that couldn&#8217;t be done if MVC Turbine picked one IoC container.</p>
<p><strong>One Final Point</strong></p>
<p>I know that bringing in an ILazy&lt;T&gt; as a dependency might be the wrong place to implement the &#8220;laziness.&#8221;  However, sometimes we&#8217;re put in less-than-ideal situations (like this routing example), and in those places I want to go with the simplest, testable solution.  I&#8217;ll strongly recommend that you <strong>NOT </strong>throw ILazy&lt;T&gt; dependencies all over your application.</p>
<p><a href="http://github.com/darrencauthon/MvcTurbine.Laziness">Get MvcTurbine.Laziness here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cauthon.com/2010/06/03/mvcturbine-laziness-and-leveraging-a-csl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatic Fluent Validation Integration into ASP.NET MVC with MvcTurbine.FluentValidation</title>
		<link>http://www.cauthon.com/2010/05/24/mvcturbine-fluentvalidation/</link>
		<comments>http://www.cauthon.com/2010/05/24/mvcturbine-fluentvalidation/#comments</comments>
		<pubDate>Tue, 25 May 2010 03:12:37 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[aspnetmvc]]></category>
		<category><![CDATA[fluentvalidation]]></category>
		<category><![CDATA[mvcturbine]]></category>

		<guid isPermaLink="false">http://www.cauthon.com/?p=819</guid>
		<description><![CDATA[I&#8217;m a big fan of Fluent Validation, a .Net library written by Jeremy Skinner that makes validation easy and understandable.  If you&#8217;ve never seen it, here&#8217;s a quick example that should explain it: public class LoginInputModelValidator : AbstractValidator&#60;LoginInputModel&#62;{ public LoginInputModelValidator() { RuleFor(x=&#62;x.Email).NotEmpty(); RuleFor(x=&#62;x.Password).NotEmpty(); } } That&#8217;s all there is to validating a login form, at [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a big fan of <a title="Fluent Validation" href="http://fluentvalidation.codeplex.com" target="_blank">Fluent Validation</a>, a .Net library written by Jeremy Skinner that makes validation easy and understandable.  If you&#8217;ve never seen it, here&#8217;s a quick example that should explain it:</p>
<pre lang="C#">public class LoginInputModelValidator : AbstractValidator&lt;LoginInputModel&gt;{
   public LoginInputModelValidator() {
      RuleFor(x=&gt;x.Email).NotEmpty();
      RuleFor(x=&gt;x.Password).NotEmpty();
   }
}</pre>
<p>That&#8217;s all there is to validating a login form, at least to the point to making sure the email and password were both entered.  See how easy that is?  But the thing is&#8230; how do you use it with ASP.NET MVC2?  How do you make its use seamless with the framework?</p>
<p>Well, like most, I started with Jeremy Skinner&#8217;s post on MVC2 integration.  He <a href="http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/" target="_blank">explains how to create your own IValidatorFactory and what code to enter in your global.asax file</a>.  Great help, but couldn&#8217;t it be easier?  Do I really want to copy bits of code here and there in each MVC project?  What if I switch IoC containers?  It works, but it didn&#8217;t feel like a complete solution to me.</p>
<p>So&#8230; I put it on myself to come up with the solution I wanted.  I&#8217;m also a big fan of <a title="MVC Turbine" href="http://mvcturbine.codeplex.com" target="_blank">MVC Turbine</a>, a project that integrates IoC throughout your MVC application (which is essential).  MVC Turbine offers the concept of a &#8220;blade&#8221; that lets you inject code into the startup and the setup of your favorite IoC container.  Essentially, it gives you one place to inject functionality that can then be used throughout your application.  Functionality like&#8230; implementing Fluent Validation into your MVC application!</p>
<h3>MvcTurbine.FluentValidation</h3>
<p>My solution is MvcTurbine.FluentValidation, and the source and binary can be found at <a href="http://github.com/darrencauthon/MvcTurbine.FluentValidation" target="_blank">here on GitHub</a>.  In order to use it to automatically validate your MVC app, you&#8217;ll need to do the following:</p>
<p>1.)  <span style="text-decoration: underline;"><a href="http://mvcturbine.codeplex.com/wikipage?title=TurbineIntro&amp;referringTitle=Documentation" target="_blank">Setup your ASP.NET MVC application to use MVC Turbine (which you should do anyway)</a>.</span></p>
<p>2.)  <span style="text-decoration: underline;">Add a reference to MvcTurbine.FluentValidation.dll.</span></p>
<p>That&#8217;s it.  Really, that&#8217;s it.  By adding MvcTurbine.FluentValidation.dll to your application. MVC Turbine will add the FluentValidationBlade to your application startup.  That blade will scan your project for validators, create an implementation of the IValidatorFactory using your preferred IoC container, create an model validator provider, and incorporate everything into the application.  And to top it all off, it will instantiate your validators through your IoC container, giving you the ability to add dependencies like this:</p>
<pre lang="C#">public class LoginInputModelValidator : AbstractValidator{
   public LoginInputModelValidator(IMembershipService membershipService) {
      RuleFor(x=&gt;x.Email).NotEmpty();
      RuleFor(x=&gt;x.Password).NotEmpty();
      RuleFor(x=&gt;x.Email).CheckThatThisIsAValidEmail(membershipService);
      RuleFor(x=&gt;x.Password).CheckThatThisIsAValidPassword(membershipService);
   }
}</pre>
<p>The blade and Turbine does everything for you, leaving you to just use it.  If I added MvcTurbine.FluentValidation to my project, simply having that validator somewhere in my project is all it takes to integrate it with an action that needs it, like this:</p>
<pre lang="C#">[HttpPost]
public ActionResult Index(LoginInputModel inputModel)
{
   if (ModelState.IsValid == false)
      return View("Index");
   membershipService.LogInAsUser(inputModel.Email, inputModel.Password);
   return RedirectToTheHomePage();
}</pre>
<p>My validator will have run before the Index action was invoked, and ModelState will be loaded with any errors from the validator.  The validator even checked the email &amp; password combination, keeping my controller clean.  Easy as pie.</p>
<h3>The Bigger Picture</h3>
<p><strong> </strong>If you look at the code to this library, you&#8217;ll see a grand total of three classes.  There&#8217;s not much there.  I&#8217;m leveraging what Fluent Validation, MVC Turbine, ASP.NET MVC, and the many .Net IoC containers  already offer.  I think there is something special here, though, and it&#8217;s MVC Turbine&#8217;s role as the glue holding them all together.  By hooking into the ASP.NET MVC Pipeline at the appropriate places and abstracting away the registering and resolving of classes from the IoC container, it makes these types of integrations possible.  I&#8217;ve written a few of these integrations, and I can tell you &#8212; they all, pretty much, turn out like this.  You just get what you need into the right spots, and then you move on.</p>
<p>It deserves more discussion than I can give now, but that&#8217;s a more important point than this particular solution.  If you have integrations in MVC where you find yourself having to edit things in multiple places, or if you find yourself continually running to global.asax everytime you want to change something, you need to give MVC Turbine a look.</p>
<p><a href="http://github.com/darrencauthon/MvcTurbine.FluentValidation/downloads" target="_blank">Download MvcTurbine.FluentValidation here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cauthon.com/2010/05/24/mvcturbine-fluentvalidation/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
