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

<channel>
	<title>Agile at Work &#187; NHibernate</title>
	<atom:link href="http://www.agileatwork.com/tag/nhibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agileatwork.com</link>
	<description>by Michael Valenty</description>
	<lastBuildDate>Sat, 10 Sep 2011 14:35:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Bolt-on Multi-Tenancy in ASP.NET MVC with Unity and NHibernate: Part II &#8211; Commingled Data</title>
		<link>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/</link>
		<comments>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/#comments</comments>
		<pubDate>Sat, 18 Jun 2011 15:03:05 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Open Closed Principle]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=580</guid>
		<description><![CDATA[Last time I went over going from separate web applications per tenant to a shared web application for all tenants, but each tenant still had its own database. Now we’re going to take the next step and let multiple tenants share the same database. After we add tenant_id to most of the tables in our [...]]]></description>
			<content:encoded><![CDATA[<p>Last time I went over going <a href="http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/">from separate web applications per tenant to a shared web application for all tenants</a>, but each tenant still had its own database. Now we’re going to take the next step and let multiple tenants share the same database. After we add <font size="2" face="Courier New">tenant_id</font> to most of the tables in our database we’ll need the application to take care of a few things.</p>
<p>First, we need to apply a where clause to all queries to ensure that each tenant sees only their data. This is pretty painless with NHibernate and completely transparent to the existing application! We just have to define a parameterized filter:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">hibernate-mapping</span><span style="color: blue"> </span><span style="color: red">xmlns</span><span style="color: blue">=</span>&quot;<span style="color: blue">urn:nhibernate-mapping-2.2</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">filter-def</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">filter-param</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">id</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">System.Int32</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">filter-def</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">hibernate-mapping</span><span style="color: blue">&gt;</span></pre>
</div>
<p>And then apply it to each entity:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">class</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">User</span>&quot;<span style="color: blue"> </span><span style="color: red">table</span><span style="color: blue">=</span>&quot;<span style="color: blue">[user]</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">id</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Id</span>&quot;<span style="color: blue"> </span><span style="color: red">column</span><span style="color: blue">=</span>&quot;<span style="color: blue">user_id</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">generator</span><span style="color: blue"> </span><span style="color: red">class</span><span style="color: blue">=</span>&quot;<span style="color: blue">identity</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">id</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">property</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Username</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">property</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Email</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="background-color: #ffffc0; margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">filter</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant</span>&quot;<span style="color: blue"> </span><span style="color: red">condition</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant_id = :id</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">class</span><span style="color: blue">&gt;</span></pre>
</div>
<p>The last step is to set the value of the filter at runtime. This is done on the <font size="2" face="Courier New">ISession</font> like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> session = c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;().OpenSession();</pre>
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.EnableFilter(<span style="color: #a31515">&quot;tenant&quot;</span>).SetParameter(<span style="color: #a31515">&quot;id&quot;</span>, c.Resolve&lt;<span style="color: #2b91af">Tenant</span>&gt;().Id);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>The current tenant comes from <font size="2" face="Courier New">c.Resolve&lt;Tenant&gt;()</font>. In order for that to work, you have to tell Unity how to find the current tenant. In ASP.NET MVC, we can look at the host header on the request and find our tenant that way. We could just as easily use another strategy though. Maybe if this were a WCF service, we could use an authentication header to establish the current tenant context. You could build out some interfaces and strategies around establishing the current tenant context, however for this article I’ll just bang it out.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">Tenant</span>&gt;(<span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> repository = c.Resolve&lt;<span style="color: #2b91af">ITenantRepository</span>&gt;();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> context = c.Resolve&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = context.Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>] ?? context.Request.Url.Host;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> repository.FindByHost(host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }));</pre>
</div>
<p>Second, we have to set the <font size="2" face="Courier New">tenant_id</font> when new entities are saved. This is a bit more complicated with NHibernate and requires a bit of a concession in that we have to add a field to the entity in order for NHibernate to know how to persist the value. I’m using a private nullable int for this.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">User</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">int</span>? tenantId;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">int</span> Id { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Username { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Email { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>It’s private because I don’t want the business logic to deal with it and it’s nullable because my tenant table is in a separate database which means I can’t lean on the data model to enforce referential integrity. That’s a problem because the default value for an integer is zero which could be happily saved by the database. By making it nullable I can be sure the database will blow up if the <font size="2" face="Courier New">tenant_id</font> is not set.</p>
<p>So, back to the issue at hand. The <font size="2" face="Courier New">tenant_id</font> needs to be set when the entity is saved. For this, I’m using an interceptor and setting the value in the <font size="2" face="Courier New">OnSave</font> method:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MultiTenantInterceptor</span> : <span style="color: #2b91af">EmptyInterceptor</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Tenant</span>&gt; tenant;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> MultiTenantInterceptor(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Tenant</span>&gt; tenant)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.tenant = tenant;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> OnSave(<span style="color: blue">object</span> entity... <span style="color: blue">object</span>[] state, <span style="color: blue">string</span>[] propertyNames...)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> index = <span style="color: #2b91af">Array</span>.IndexOf(propertyNames, <span style="color: #a31515">&quot;tenantId&quot;</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (index == -1)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenant().Id;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; state[index] = tenantId;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; entity</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .GetType()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .GetField(<span style="color: #a31515">&quot;tenantId&quot;</span>, <span style="color: #2b91af">BindingFlags</span>.Instance | <span style="color: #2b91af">BindingFlags</span>.NonPublic)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetValue(entity, tenantId);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>This <font size="2" face="Courier New">IInterceptor</font> mechanism is a little wonky. If you change any data, you have to do it in both the entity instance and the <font size="2" face="Courier New">state</font> array that NHibernate uses to hydrate entities. It’s not a big deal, it’s just one of those things you have to accept like the fact that Apple and Google are tracking your every move via your smart phone. Oh, and the interceptor gets wired up like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ContainerControlledLifetimeManager</span>(),</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>()</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetInterceptor(<span style="color: blue">new</span> <span style="color: #2b91af">MultiTenantInterceptor</span>(() =&gt; c.Resolve&lt;<span style="color: #2b91af">Tenant</span>&gt;()))</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>We’re almost done. There is one more case that needs to be handled. When NHibernate loads an entity by its primary key, it doesn’t run through the query engine which means the tenant filter isn’t applied. Fortunately, we can take care of this in the interceptor:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MultiTenantInterceptor</span> : <span style="color: #2b91af">EmptyInterceptor</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; ...</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> OnLoad(<span style="color: blue">object</span> entity... <span style="color: blue">object</span>[] state, <span style="color: blue">string</span>[] propertyNames...)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> index = <span style="color: #2b91af">Array</span>.IndexOf(propertyNames, <span style="color: #a31515">&quot;tenantId&quot;</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (index == -1)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> entityTenantId = <span style="color: #2b91af">Convert</span>.ToInt32(state[index]);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> currentTenantId = tenant().Id;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (entityTenantId != currentTenantId)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">AuthorizationException</span>(<span style="color: #a31515">&quot;Permission denied to {0}&quot;</span>, entity);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>That’s it. Have fun and happy commingling.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Bolt-on Multi-Tenancy in ASP.NET MVC with Unity and NHibernate</title>
		<link>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/</link>
		<comments>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/#comments</comments>
		<pubDate>Sat, 14 May 2011 15:59:32 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Open Closed Principle]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=564</guid>
		<description><![CDATA[The Mission: 
Build a web application as though it’s for a single customer (tenant) and add multi-tenancy as a bolt-on feature by writing only new code. There are flavors of multi-tenancy, in this case I want each tenant to have its own database but I want all tenants to share the same web application and [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Mission:</strong> </p>
<p>Build a web application as though it’s for a single customer (tenant) and add multi-tenancy as a bolt-on feature by writing only new code. There are flavors of multi-tenancy, in this case I want each tenant to have its own database but I want all tenants to share the same web application and figure out who’s who by looking at the host header on the http request.</p>
<p><strong>The Plan:</strong></p>
<p>To pull this off, we’re going to have to rely on our SOLID design principles, especially Single Responsibility and Dependency Inversion. We’ll get some help from these frameworks:</p>
<ul>
<li><a href="http://www.asp.net/mvc">ASP.NET MVC</a> </li>
<li><a href="http://unity.codeplex.com/">Unity</a> </li>
<li><a href="http://nhforge.org/Default.aspx">NHibernate</a> </li>
</ul>
<p><strong>Game on:</strong></p>
<p>Let’s take a look at a controller that uses NHibernate to talk to the database. I’m not going to get into whether you should talk directly to NHibernate from the controller or go through a service layer or repository because it doesn’t affect how we’re going to add multi-tenancy. The important thing here is that the <font size="2" face="Courier New">ISession</font> is <em>injected</em> into the controller, and we aren’t using the service locator pattern to request the <font size="2" face="Courier New">ISession</font> from a singleton.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UserController</span> : <span style="color: #2b91af">Controller</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISession</span> session;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> UserController(<span style="color: #2b91af">ISession</span> session)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.session = session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ActionResult</span> Edit(<span style="color: blue">int</span> id)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> user = session.Load&lt;<span style="color: #2b91af">User</span>&gt;(id);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> View(user);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Alright, now it’s time to write some new code and make our web application connect to the correct database based on the host header in the http request. First, we’ll need a database to store a list of tenants along with the connection string for that tenant’s database. Here’s my entity:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Tenant</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Host { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> ConnectionString { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>I’ll use the repository pattern here so there is a crisp consumer of the <font size="2" face="Courier New">ISession</font> that connects to the lookup database rather than one of the tenant shards. This will be important later when we go to configure Unity.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">NHibernateTenantRepository</span> : <span style="color: #2b91af">ITenantRepository</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISession</span> session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">HttpContextBase</span> context;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> NHibernateTenantRepository(<span style="color: #2b91af">ISession</span> session, <span style="color: #2b91af">HttpContextBase</span> context)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.session = session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.context = context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">Tenant</span> Current</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span></pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = context.Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>];</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> FindByHost(host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">Tenant</span> FindByHost(<span style="color: blue">string</span> host)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Query&lt;<span style="color: #2b91af">Tenant</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SingleOrDefault(t =&gt; t.Host == host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>So now we need a dedicated <font size="2" face="Courier New">ISessionFactory</font> for the lookup database and make sure that our <font size="2" face="Courier New">NHibernateTenantRepository</font> gets the right <font size="2" face="Courier New">ISession</font> . It’s not too bad, we just need to name them in the container so we can refer to them explicitly.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session_factory&quot;</span>,</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ContainerControlledLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>().Configure().BuildSessionFactory())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session&quot;</span>,</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(<span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session_factory&quot;</span>).OpenSession())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ITenantRepository</span>, <span style="color: #2b91af">NHibernateTenantRepository</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">NHibernateTenantRepository</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionConstructor</span>(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ResolvedParameter</span>&lt;<span style="color: #2b91af">ISession</span>&gt;(<span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session&quot;</span>),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ResolvedParameter</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; )</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>Hopefully that’s about what you were expecting since it’s not really the interesting part. The more interesting part is configuring the <font size="2" face="Courier New">ISession</font> that gets injected into the <font size="2" face="Courier New">UserController</font> to connect to a different database based on the host header in the http request. The Unity feature we’re going to leverage for this is the <font size="2" face="Courier New">LifetimeManager</font>. This is an <a href="http://www.agileatwork.com/captcha-and-inversion-of-control/">often overlooked feature</a> of IoC containers.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="background-color: #ffffc0; color: #2b91af">PerHostLifetimeManager</span>(() =&gt; <span style="color: blue">new</span> <span style="color: #2b91af">HttpContextWrapper</span>(<span style="color: #2b91af">HttpContext</span>.Current)),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> connString = c</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Resolve&lt;<span style="color: #2b91af">ITenantRepository</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Current</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .ConnectionString;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetProperty(NHibernate.Cfg.<span style="color: #2b91af">Environment</span>.ConnectionString, connString)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }));</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt; c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;().OpenSession())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>Here we’re using a custom <font size="2" face="Courier New">PerHostLifetimeManager</font>. This tells Unity to maintain a session factory per host. When Unity runs across a host it doesn’t have a session factory for, it will run the <font size="2" face="Courier New">InjectionFactory</font> block to create one using the connection string associated with that tenant.</p>
<p>Since multiple simultaneous requests will be trying to get and set values <em>with the same key</em>, we need to make sure our <font size="2" face="Courier New">PerHostLifetimeManager</font> is thread safe. That’s pretty easy since Unity comes with a <font size="2" face="Courier New">SynchronizedLifetimeManager</font> base class that takes care of the fact that <font size="2" face="Courier New">Dictionary</font> <a href="http://stackoverflow.com/questions/157933/whats-the-best-way-of-implementing-a-thread-safe-dictionary-in-net">isn’t thread safe</a>.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">PerHostLifetimeManager</span> : <span style="background-color: #ffffc0; color: #2b91af">SynchronizedLifetimeManager</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt; context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; store;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> PerHostLifetimeManager(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt; context)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.context = context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; store = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">object</span> SynchronizedGetValue()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = GetHost();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!store.ContainsKey(host))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">null</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> store[host];</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> SynchronizedSetValue(<span style="color: blue">object</span> newValue)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; store[GetHost()] = newValue;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">string</span> GetHost()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> context().Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>];</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>So what did we accomplish? Well we didn’t touch any of our existing application code. We just wrote new code and through configuration we added multi-tenancy! That’s pretty cool, but was it worth it? Well, the goal in itself isn’t super important, but this exercise can certainly highlight areas of your codebase where you might be violating the single responsibility principle or leaking too many infrastructure concepts into your application logic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Rafactoring: Introduce Parameter Object</title>
		<link>http://www.agileatwork.com/rafactoring-introduce-parameter-object/</link>
		<comments>http://www.agileatwork.com/rafactoring-introduce-parameter-object/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 23:59:06 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Introduce Parameter Object]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=412</guid>
		<description><![CDATA[Take a look at this function:
public UserIndexViewModel GetIndexViewModel(int pageSize, int pageNumber) {
    var model = new UserIndexViewModel();

    var allUsers = Session.CreateCriteria&#60;User&#62;();

    model.Total = CriteriaTransformer
        .TransformToRowCount(allUsers)
        .UniqueResult&#60;int&#62;();

    model.Users = allUsers
 [...]]]></description>
			<content:encoded><![CDATA[<p>Take a look at this function:</p>
<pre class="prettyprint"><code>public UserIndexViewModel GetIndexViewModel(int pageSize, int pageNumber) {
    var model = new UserIndexViewModel();

    var allUsers = Session.CreateCriteria&lt;User&gt;();

    model.Total = CriteriaTransformer
        .TransformToRowCount(allUsers)
        .UniqueResult&lt;int&gt;();

    model.Users = allUsers
        .SetFirstResult(pageSize * (pageNumber - 1) + 1)
        .SetMaxResults(pageSize)
        .AddOrder&lt;User&gt;(u =&gt; u.LastName, Order.Asc)
        .List&lt;User&gt;();

    return model;
}</code></pre>
<p>There isn’t much going on here, but it could be better. I&#8217;m looking at the arguments <font size="2" face="Courier New">pageSize</font> and <font size="2" face="Courier New">pageNumber</font>. Notice how they both start with the prefix “page”. That’s a smell. The common prefix means the arguments are related, so let’s apply the <em>Introduce Parameter Object</em> refactoring and see what happens.</p>
<pre class="prettyprint"><code>public class Page {
    private readonly int number;
    private readonly int size;

    public Page(int number, int size) {
        this.number = number;
        this.size = size;
    }

    public int Size {
        get { return size; }
    }

    public int Number {
        get { return number; }
    }

    public int FirstResult {
        get { return size * (number - 1) + 1; }
    }
}</code></pre>
<p>What did we accomplish?</p>
<ul>
<li>Creating the parameter object gave us a place to put the logic of calculating the first result of the current page. This logic would otherwise be scattered around the application and even though it’s simple, it’s error prone.</li>
<li>The logic of calculating the first result is testable.</li>
</ul>
<pre class="prettyprint"><code>[Test]
public void Should_calculate_first_result_of_current_page() {
    Assert.That(new Page(1, 20).FirstResult, Is.EqualTo(1));
    Assert.That(new Page(2, 20).FirstResult, Is.EqualTo(21));
    Assert.That(new Page(3, 20).FirstResult, Is.EqualTo(41));
}</code></pre>
<p>It’s not rocket science, but it still deserves a test. Our other option is spinning up <a href="http://www.asp.net/Downloads/archived/cassini/">Cassini</a> and clicking around to make sure we got it right. That’s just silly. A little piece of me dies each time I press F5 to run a manual test.</p>
<p>Anyway, there is this thing that happens with single responsibility classes. Because their purpose is crisp, it draws out robustness. In this case, I&#8217;m thinking about what we should we do if we get zero or a negative value for page number. I’m a fail fast kind of guy, so I’d probably go with a guard clause.</li>
</p>
<pre class="prettyprint"><code>public Page(int number, int size) {
    GuardAgainstLessThanOne(number);
    ...
}</code></pre>
<p>But you could silently correct it if that&#8217;s how you roll:</p>
<pre class="prettyprint"><code>public int Number {
    get { return Math.Max(1, number); }
}</code></pre>
<p>The point is that this is an obvious scenario to consider when looking at such a special purpose object. All too often though, bits of logic are mixed together like 32 kindergarteners sitting next to each other on a rug during a lesson. The room is one fart or tickle away from erupting into total kaos. It&#8217;s roughly half teaching and half crowd control, only without the rubber bullets and pepper spray. Not surprisingly, overcrowded classrooms don&#8217;t work that well and over-ambitous functions don&#8217;t work that well either. Each little bit of logic needs some one on one with you. Give it a chance to be all it can be by pulling it aside and getting to know it a little better. You might be surprised.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/rafactoring-introduce-parameter-object/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Maybe Uncle Bob is Wrong About Testing</title>
		<link>http://www.agileatwork.com/maybe-uncle-bob-is-wrong-about-testing/</link>
		<comments>http://www.agileatwork.com/maybe-uncle-bob-is-wrong-about-testing/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 06:09:46 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=218</guid>
		<description><![CDATA[As pressure increases, testing decreases. As the testing decreases, errors increase and as errors increase, pressure increases more. This is what’s known as a positive feedback loop, and this was how I spent the better part of last week.
&#160;
Figure A.5 Not enough time to test reduces the available time     Test-Driven Development: [...]]]></description>
			<content:encoded><![CDATA[<p>As pressure increases, testing decreases. As the testing decreases, errors increase and as errors increase, pressure increases more. This is what’s known as a positive feedback loop, and this was how I spent the better part of last week.</p>
<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="feedback2" border="0" alt="feedback2" src="http://www.agileatwork.com/wp-content/uploads/2009/11/feedback2_thumb.png" width="165" height="123" /></p>
<p><strong>Figure A.5</strong> <em>Not enough time to test reduces the available time </em>    <br /><font size="2"><a href="http://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530">Test-Driven Development: By Example</a> by Kent Beck</font></p>
<p>It didn’t start out that way. In fact the first few lines of code I wrote were tests. The problem was I could only get about an hour or two in each night and every day that passed we were leaving money on the table.</p>
<p>Since I didn’t have much time at night, I didn’t want to spend it writing tests. I just wanted to get the app done. All I needed to do was sync business listings from an affiliate with <a href="http://www.garagecommerce.com/">GarageCommerce.com</a>, the project I’ve been working on for the last few months. There were only a handful of business rules to deal with and I thought I could just bang it out.</p>
<p><img style="border-right-width: 0px; margin: 0px 15px 0px 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="district9-poster" border="0" alt="district9-poster" align="left" src="http://www.agileatwork.com/wp-content/uploads/2009/12/district9poster_thumb.jpg" width="160" height="240" /></p>
<p>I know what you’re thinking. You already know where this is headed and you might as well just skip to the end. It’s like in that movie District 9. It started out pretty good with some edgy social commentary but by the end of the movie it just phoned in a cliché Hollywood plot. You know, like “fish out of water”, “buddy movie”, or “trading places” as was the case with District 9.</p>
<p>Anyway, I finished the app and since I only had a few tests I figured I should trace through things a few times to look for obvious problems. After doing that for a few minutes I was ready to press F5 and start working the kinks out. So after hours of zero feedback coding, I took a deep breath and the started the app for the first time.</p>
<p>It promptly bombed out as expected. I worked through a handful of errors and then it was good to go. As I watched it run, I thought to myself that <a href="http://blog.stackoverflow.com/2009/02/podcast-41/">maybe Uncle Bob is wrong about testing and Spolsky isn’t such a douche bag after all</a>. However after processing a couple hundred jobs, it started throwing crazy errors in a tight loop. Crap!</p>
<p>Fast forward a few hours and I’ve got a hunch as to what is causing the problem. The way I wired up the app, I was creating a single NHibernate session for the entire batch of jobs. I knew this could be trouble so I at least made a point to commit after each job and clear the session so it wouldn’t get bogged down with 10K+ entities. I knew the single session was smelly and the errors I was seeing prompted me to refactor.</p>
<p><img style="border-right-width: 0px; margin: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="MASH-tv-show-11" border="0" alt="MASH-tv-show-11" src="http://www.agileatwork.com/wp-content/uploads/2009/12/MASHtvshow11_thumb.jpg" width="240" height="163" /></p>
<p>This is where it got ugly. I needed to do a pretty major overhaul and I was mostly test-less. My blood pressure went way up with each change and the fact that I didn’t have tests just made me take larger steps with no safety net. I felt like a M.A.S.H. surgeon with guts all over the operating table. Part of me thought I should take a few steps back and regroup, but another part of me was reminded of this quote:</p>
<blockquote><p>If you’re going through hell, keep going. – Winston Churchill</p>
</blockquote>
<p>So I stuck with it and got ‘er done, but it wasn’t much fun. What did I take from this experience? No revelations really, just some common sense reinforcement. It’s like rediscovering that diet and exercise is the key to losing weight, except that I rediscovered that not having tests really sucks when you have to make changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/maybe-uncle-bob-is-wrong-about-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integration Testing with NHibernate</title>
		<link>http://www.agileatwork.com/integration-testing-with-nhibernate/</link>
		<comments>http://www.agileatwork.com/integration-testing-with-nhibernate/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 22:12:34 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Integration Testing]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=195</guid>
		<description><![CDATA[While the first-level cache in NHibernate is great for production, it can be super annoying for integration tests. Basically I just want to make sure my mapping works and that when I save an entity it goes to the database.

[TestFixture]
public class MyIntegrationFixture : IntegrationFixture {
&#160;&#160;&#160; [Test]
&#160;&#160;&#160; public void Can_add_elements() {
&#160;&#160;&#160; &#160;&#160;&#160; var repository = Container.Resolve&#60;IRepository&#60;MyEntity&#62;&#62;();
&#160;
&#160;&#160;&#160; [...]]]></description>
			<content:encoded><![CDATA[<p>While the first-level cache in NHibernate is great for production, it can be super annoying for integration tests. Basically I just want to make sure my mapping works and that when I save an entity it goes to the database.</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">TestFixture</span>]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">MyIntegrationFixture</span> : <span style="color: #2b91af;">IntegrationFixture</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">Test</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">void</span> Can_add_elements() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> repository = Container.Resolve&lt;<span style="color: #2b91af;">IRepository</span>&lt;<span style="color: #2b91af;">MyEntity</span>&gt;&gt;();</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> entity = repository.FindById(1);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; entity.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">Element</span> { Description = <span style="color: #a31515;">&quot;The Description&quot;</span> });</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; repository.Save(entity);</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: #2b91af;">Assert</span>.That(repository.FindById(1).Elements.Count(), <span style="color: #2b91af;">Is</span>.EqualTo(1));</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
<p>The problem is the next time I call <font face="Courier New" size="2">FindById()</font> I get my object back from the first level cache (<font face="Courier New" size="2">ISession</font>), so the Assert passes but looking at the SQL output by NHibernate I can see that no INSERT statement is happening. There are two things that NHibernate needs to do in order for the integration test to work as expected.</p>
<ol>
<li>There needs to be an explicit transaction and it needs to be committed in order to actually send the INSERT statements to the database. </li>
<li>The entity needs to be evicted from the session in order to ensure that the next call to <font face="Courier New" size="2">FindById()</font> actually goes to the database. </li>
</ol>
<p>It’s the job of the application to manage the scope of the unit of work. Typically this is per web request in a web app. In a test, it’s per test. This turns into a bunch of boiler-plate noise. Also, this business about evicting the session is an NHibernate specific thing and doesn’t belong in a test that is dealing with an <font face="Courier New" size="2">IRepository</font> abstraction.</p>
<p>Since I solve all my problems with a <a href="http://www.agileatwork.com/an-order-processing-pipeline-in-aspnet-mvc/">pipeline</a> or decorator, I figured I’d <a href="http://www.agileatwork.com/wp-content/uploads/2010/03/SessionDecorator.zip">decorate the <font face="Courier New" size="2">ISession</font></a> and commit and evict on the operations I care about:</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">AutoCommitAndEvictSession</span> : <span style="color: #2b91af;">SessionDecorator</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> AutoCommitAndEvictSession(<span style="color: #2b91af;">ISession</span> session)</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; : <span style="color: blue;">base</span>(session) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">object</span> Save(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">object</span> result;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> tx = Session.BeginTransaction()) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; result = Session.Save(obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tx.Commit();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Evict(obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> result;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> Update(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.Update, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> SaveOrUpdate(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.SaveOrUpdate, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">override</span> <span style="color: blue;">void</span> Delete(<span style="color: blue;">object</span> obj) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; CommitAndEvict(<span style="color: blue;">base</span>.Delete, obj);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">void</span> CommitAndEvict(<span style="color: #2b91af;">Action</span>&lt;<span style="color: blue;">object</span>&gt; action, <span style="color: blue;">object</span> entity) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> tx = Session.BeginTransaction()) {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; action.Invoke(entity);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; tx.Commit();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Session.Evict(entity);</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
<p>Then I just work it into a test fixture like this:</p>
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;">
<pre style="margin: 0px;">[<span style="color: #2b91af;">TestFixture</span>]</pre>
<pre style="margin: 0px;"><span style="color: blue;">public</span> <span style="color: blue;">abstract</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">IntegrationFixture</span> {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">protected</span> <span style="color: #2b91af;">IUnityContainer</span> Container { <span style="color: blue;">get</span>; <span style="color: blue;">private</span> <span style="color: blue;">set</span>; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TestFixtureSetUp</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TestFixtureSetUp() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container = <span style="color: blue;">new</span> <span style="color: #2b91af;">UnityContainer</span>()</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; .AddNewExtension&lt;<span style="color: #2b91af;">ConfigureNHibernate</span>&gt;();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TestFixtureTearDown</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TestFixtureTearDown() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container.Dispose();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">SetUp</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> SetUp() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> session = Container.Resolve&lt;<span style="color: #2b91af;">ISessionFactory</span>&gt;().OpenSession();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="background-color: #ffffcc">Container.RegisterInstance&lt;<span style="color: #2b91af;">ISession</span>&gt;(<span style="color: blue;">new</span> <span style="color: #2b91af;">AutoCommitAndEvictSession</span>(session));</style>
</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">&nbsp;</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; [<span style="color: #2b91af;">TearDown</span>]</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span> <span style="color: blue;">virtual</span> <span style="color: blue;">void</span> TearDown() {</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Container.Resolve&lt;<span style="color: #2b91af;">ISession</span>&gt;().Dispose();</pre>
<pre style="margin: 0px;">&nbsp;&nbsp;&nbsp; }</pre>
<pre style="margin: 0px;">}</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/integration-testing-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Unit of Work with Unity and ASP.NET MVC</title>
		<link>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/</link>
		<comments>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/#comments</comments>
		<pubDate>Sun, 10 May 2009 07:58:14 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://blog.agileatwork.com/?p=9</guid>
		<description><![CDATA[I was recently asked how I get the context of&#160; “this” in the UoW relating to the current page request.
 
Before I get into the guts, I would like to provide a little context. My application has 20+ databases scattered across 4 machines.

IRepository&#60;Customer&#62; customerRepository; // customer database on server 1
IRepository&#60;Package&#62;  packageRepository; // customer database [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked how I get the context of&#160; “this” in the UoW relating to the current page request.</p>
<p><a href="http://blog.agileatwork.com/wp-content/uploads/2009/05/howididit.jpg"><img title="howididit" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="179" alt="howididit" src="http://blog.agileatwork.com/wp-content/uploads/2009/05/howididit-thumb.jpg" width="240" border="0" /></a> </p>
<p>Before I get into the guts, I would like to provide a little context. My application has 20+ databases scattered across 4 machines.</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">IRepository&lt;Customer&gt; customerRepository; <span class="rem">// customer database on server 1</span>
IRepository&lt;Package&gt;  packageRepository; <span class="rem">// customer database on server 1</span>
IRepository&lt;Contact&gt;  contactRepository; <span class="rem">// contact database on server 2</span></pre>
<div>So, I might ask for a Customer object and a Package object and I want to get the same ISession for both and if I ask for the same Customer twice, I want to get the one from the 1st level cache (I’m using NHibernate). If I ask for a Contact object, I will get a different ISession. All opened sessions are managed by my UoW. So, when the page request is complete, I call UoW.Commit and all sessions are committed.</div>
<p>The “magic” if you will, happens in the global.asax. I was nosing around in Rhino.Commons for inspiration and adapted a technique I saw there. This is how it looks:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> GlobalApplication : HttpApplication
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IUnityContainer container;

    <span class="kwrd">public</span> GlobalApplication()
    {
        BeginRequest += <span class="kwrd">new</span> EventHandler(GlobalApplication_BeginRequest);
        EndRequest += <span class="kwrd">new</span> EventHandler(GlobalApplication_EndRequest);
    }

    <span class="kwrd">protected</span> <span class="kwrd">void</span> Application_Start(<span class="kwrd">object</span> sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);

        container = <span class="kwrd">new</span> UnityContainer();
        container.AddNewExtension&lt;PolicyInjectorContainerExtension&gt;();
        container.AddNewExtension&lt;HttpRequestLifetimeCoreContainerExtension&gt;();
        container.AddNewExtension&lt;WebMvcContainerExtension&gt;();

        ControllerBuilder.Current.SetControllerFactory(<span class="kwrd">new</span> UnityControllerFactory(container));
    }

    <span class="kwrd">void</span> GlobalApplication_BeginRequest(<span class="kwrd">object</span> sender, EventArgs e)
    {
        var unitOfWork = container.Resolve&lt;IUnitOfWork&gt;();
        unitOfWork.Start();
    }

    <span class="kwrd">void</span> GlobalApplication_EndRequest(<span class="kwrd">object</span> sender, EventArgs e)
    {
        var unitOfWork = container.Resolve&lt;IUnitOfWork&gt;();
        unitOfWork.Commit();
    }
}</pre>
<p>I register the UoW with an HttpRequestLifetimeManager so I get a new instance for each request.</p>
<pre class="csharpcode">Container.RegisterType&lt;IUnitOfWork&lt;ISession&gt;,
	NHibernateUnitOfWork&gt;(<span class="kwrd">new</span> HttpRequestLifetimeManager());</pre>
<div>My NHibernateRepository gets injected with the UoW for the current HttpRequest and when the request is complete, the global.asax commits the whole thing.</div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> NHibernateRepository&lt;T&gt; : IRepository&lt;T&gt;
{
    <span class="kwrd">protected</span> ISession session;

    <span class="kwrd">public</span> NHibernateRepository(IUnitOfWork&lt;ISession&gt; unitOfWork)
    {
        session = unitOfWork.GetContextFor&lt;T&gt;();
    }

    ...

    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> Save(T obj)
    {
        session.Save(obj);
    }
}</pre>
<p>Now, this is all the context of an ASP.NET MVC Controller, but I have a similar issue for other (non-web) services. In that context I am using AOP and decorating a particular method with [UnitOfWork], which looks like:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> UnitOfWorkCallHander : ICallHandler
{
    <span class="kwrd">private</span> IUnitOfWork&lt;ISession&gt; unitOfWork;

    <span class="kwrd">public</span> UnitOfWorkCallHander(IUnitOfWork&lt;ISession&gt; unitOfWork)
    {
        <span class="kwrd">this</span>.unitOfWork = unitOfWork;
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Order { get; set; }

    <span class="kwrd">public</span> IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        unitOfWork.Start();

        <span class="kwrd">try</span>
        {
            <span class="kwrd">return</span> getNext()(input, getNext);
        }
        <span class="kwrd">finally</span>
        {
            unitOfWork.Commit();
        }
    }
}</pre>
<p>In that context I use a PerThreadLifetimeManager for the NHibernateUnitOfWork, and code ends up looking like:</p>
<pre class="csharpcode">[UnitOfWork]
<span class="kwrd">public</span> <span class="kwrd">void</span> Process(Job job)
{
    ...
}</pre>
<p>You know, there is really no reason why you couldn’t do the same thing in the MVC context. You could basically ditch the global.asax event hooha and just annotate the Controller task:</p>
<pre class="csharpcode">[UnitOfWork]
<span class="kwrd">public</span> ActionResult ControllerTaskThatRequiresUoW()
{
    ...
}</pre>
<p>It’s more explicit than using the global.asax technique and it would allow you to specify different UoW behavior on each controller task:</p>
<pre class="csharpcode">[UnitOfWork(IsolationLevel.ReadCommitted]
<span class="kwrd">public</span> ActionResult SomeTaskThatShouldNotReadUncommitedData()
{
}

[UnitOfWork(IsolationLevel.ReadUncommitted)]
<span class="kwrd">public</span> ActionResult AnotherTaskWithDifferentRequirements()
{
}</pre>
<p>I’d like to try this out next time I get back into ASP.NET MVC, the global.asax event technique felt a little too magical and I don’t think Uncle Bob would approve.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

