<?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; Unity</title>
	<atom:link href="http://www.agileatwork.com/tag/unity/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>Moq Extension Methods for Unity</title>
		<link>http://www.agileatwork.com/moq-extension-methods-for-unity/</link>
		<comments>http://www.agileatwork.com/moq-extension-methods-for-unity/#comments</comments>
		<pubDate>Sat, 31 Oct 2009 15:36:30 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/moq-extension-methods-for-unity/</guid>
		<description><![CDATA[A few people have asked about the RegisterMock extension method used in another post. The usage looks like this:
[Test]
public void Should_delete_removed_image()
{
    container.RegisterMock&#60;IFileRepository&#62;()
        .Setup(r =&#62; r.Delete(It.IsAny&#60;IFile&#62;()))
        .Verifiable();

    container.RegisterMock&#60;IBusinessRepository&#62;()
        .Setup(r [...]]]></description>
			<content:encoded><![CDATA[<p>A few people have asked about the <font face="Courier New" size="2">RegisterMock</font> extension method used in <a href="http://www.agileatwork.com/auto-mocking-unity-container-extension/">another post</a>. The usage looks like this:
<pre class="csharpcode">[Test]
<span class="kwrd">public</span> <span class="kwrd">void</span> Should_delete_removed_image()
{
    container.<span style="background: #ffffc0">RegisterMock</span>&lt;IFileRepository</span>&gt;()
        .Setup(r =&gt; r.Delete(It.IsAny&lt;IFile&gt;()))
        .Verifiable();

    container.<span style="background: #ffffc0">RegisterMock</span>&lt;IBusinessRepository&gt;()
        .Setup(r =&gt; r.FindById(3))
        .Returns(CreateBusinessWith(<span class="kwrd">new</span> BusinessImage { ImageId = 4 }));

    var controller = container.Resolve&lt;BusinessGalleryController&gt;();
    controller.Delete(3, 4);

    container.<span style="background: #ffffc0">VerifyMockFor</span>&lt;IFileRepository&gt;();
}</pre>
<p>It’s just a few helper extensions for using <a href="http://code.google.com/p/moq/">Moq</a> with <a href="http://www.codeplex.com/unity/">Unity</a> that cut down on the noise in tests. My friend Keith came up with it, I just happen to blog about it first. Here it is: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> MoqExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> Mock&lt;T&gt; RegisterMock&lt;T&gt;(<span class="kwrd">this</span> IUnityContainer container) <span class="kwrd">where</span> T : <span class="kwrd">class</span>
    {
        var mock = <span class="kwrd">new</span> Mock&lt;T&gt;();

        container.RegisterInstance&lt;Mock&lt;T&gt;&gt;(mock);
        container.RegisterInstance&lt;T&gt;(mock.Object);

        <span class="kwrd">return</span> mock;
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Use this to add additional setups for a mock that is already registered</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> Mock&lt;T&gt; ConfigureMockFor&lt;T&gt;(<span class="kwrd">this</span> IUnityContainer container) <span class="kwrd">where</span> T : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> container.Resolve&lt;Mock&lt;T&gt;&gt;();
    }

    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> VerifyMockFor&lt;T&gt;(<span class="kwrd">this</span> IUnityContainer container) <span class="kwrd">where</span> T : <span class="kwrd">class</span>
    {
        container.Resolve&lt;Mock&lt;T&gt;&gt;().VerifyAll();
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/moq-extension-methods-for-unity/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Default Interceptor for Unity</title>
		<link>http://www.agileatwork.com/default-interceptor-for-unity/</link>
		<comments>http://www.agileatwork.com/default-interceptor-for-unity/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 07:41:56 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/default-interceptor-for-unity/</guid>
		<description><![CDATA[Default: the two sweetest words in the English language – Homer Simpson

Unity interception requires you to specify what kind of interceptor to use for each type you want to intercept. This can be a little painful, so I decided to take a stab at a container extension that will apply a default interceptor with optional [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Default: the two sweetest words in the English language – Homer Simpson</p>
</blockquote>
<p>Unity interception requires you to specify what kind of interceptor to use for each type you want to intercept. This can be a little painful, so I decided to take a stab at a container extension that will apply a default interceptor with optional matching rules.</p>
<p>This is how I want it to look:</p>
<pre class="prettyprint">
<code>container
    .AddNewExtension&lt;InterceptOnRegister&gt;()
    .Configure&lt;InterceptOnRegister&gt;()
    .SetDefaultInterceptor&lt;TransparentProxyInterceptor&gt;()
    .AddMatchingRule(new AssemblyNameStartsWith("MyCompany"));</code>
</pre>
<p>The basic idea here is to subscribe to the register events and configure interception if it meets our criteria. By default it will match everything and apply <font face="Courier New" size="2">TransparentProxyInterceptor</font>, but as you can see from the snippet above, you can explicitly supply another interceptor and matching rules.</p>
<p>Here it is:</p>
<pre class="prettyprint">
<code>public class InterceptOnRegister : UnityContainerExtension {
    private IInstanceInterceptor interceptor;
    private readonly IList&lt;IInterceptRule&gt; rules;

    public InterceptOnRegister() {
        interceptor = new TransparentProxyInterceptor();
        rules = new List&lt;IInterceptRule&gt; {
            new NotUnityInterceptionAssembly(),
            new DoesNotHaveGenericMethods() };
    }

    public InterceptOnRegister AddMatchingRule(IInterceptRule rule) {
        rules.Add(rule);
        return this;
    }

    public InterceptOnRegister AddNewMatchingRule&lt;T&gt;() where T : IInterceptRule, new() {
        rules.Add(new T());
        return this;
    }

    public InterceptOnRegister SetDefaultInterceptor&lt;T&gt;() where T : IInstanceInterceptor, new() {
        interceptor = new T();
        return this;
    }

    protected override void Initialize() {
        AddInterceptionExtensionIfNotExists();

        Context.Registering +=
            (sender, e) =&gt; SetInterceptorFor(e.TypeFrom, e.TypeTo ?? e.TypeFrom);
    }

    private void AddInterceptionExtensionIfNotExists() {
        if (Container.Configure&lt;Interception&gt;() == null) {
            Container.AddNewExtension&lt;Interception&gt;();
        }
    }

    private void SetInterceptorFor(Type typeToIntercept, Type typeOfInstance) {
        if (!AllMatchingRulesApply(typeToIntercept, typeOfInstance)) {
            return;
        }

        if (interceptor.CanIntercept(typeOfInstance)) {
            Container
                .Configure&lt;Interception&gt;()
                .SetDefaultInterceptorFor(typeOfInstance, interceptor);
        } else if (interceptor.CanIntercept(typeToIntercept)) {
            Container
                .Configure&lt;Interception&gt;()
                .SetDefaultInterceptorFor(typeToIntercept, interceptor);
        }
    }

    private bool AllMatchingRulesApply(Type typeToIntercept, Type typeOfInstance) {
        foreach (var rule in rules) {
            if (!rule.Matches(typeToIntercept, typeOfInstance)) {
                return false;
            }
        }

        return true;
    }
}</code>
</pre>
<p>And you’ll need this stuff too:</p>
<pre class="prettyprint">
<code>public interface IInterceptRule {
    bool Matches(Type typeToIntercept, Type typeOfInstance);
}

public class NotUnityInterceptionAssembly : IInterceptRule {
    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return !typeToIntercept.Assembly.Equals(typeof(Interception).Assembly);
    }
}

public class DoesNotHaveGenericMethods : IInterceptRule {
    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return typeOfInstance.GetMethods().Count(m =&gt; m.IsGenericMethod) == 0;
    }
}

public class AssemblyNameStartsWith : IInterceptRule {
    private string match;

    public AssemblyNameStartsWith(string match) {
        this.match = match;
    }

    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return typeOfInstance.Assembly.FullName.StartsWith(match);
    }
}</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/default-interceptor-for-unity/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Validation with Unity Interception</title>
		<link>http://www.agileatwork.com/validation-with-unity-interception/</link>
		<comments>http://www.agileatwork.com/validation-with-unity-interception/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 20:16:19 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Composite Pattern]]></category>
		<category><![CDATA[Unity]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=149</guid>
		<description><![CDATA[ 
This is how I want things to look: 
public class UpdateUserRequest
{
    [AuthorizedUserPublisherRequired]
    public int UserId { get; set; }

    [Required(&#34;Name is required&#34;)]
    public string Name { get; set; }

    [ValidZipCodeRequired(&#34;Invalid zip code&#34;)]
    public string ZipCode { [...]]]></description>
			<content:encoded><![CDATA[<p><img title="funny_sign_5" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="237" alt="funny_sign_5" src="http://www.agileatwork.com/wp-content/uploads/2009/07/funny_sign_5.jpg" width="240" border="0" /> </p>
<p>This is how I want things to look: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> UpdateUserRequest
{
    [AuthorizedUserPublisherRequired]
    <span class="kwrd">public</span> <span class="kwrd">int</span> UserId { get; set; }

    [Required(<span class="str">&quot;Name is required&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }

    [ValidZipCodeRequired(<span class="str">&quot;Invalid zip code&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> ZipCode { get; set; }
}</pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IUserService
{
    <span class="kwrd">void</span> Update(UpdateUserRequest request);
} </pre>
<p>There are validation frameworks out there that will do this, so what’s my beef? Well, first of all I want to inject the validators with dependencies to implement the juicier rules. And second, I’m treating validation as a core concern so I don’t want a dependency on a framework like Enterprise Library. I had several questions like:</p>
<p>1) How do I get dependencies into the validators?</p>
<p>2) How do I get <font face="Courier New" size="2">ValidZipCodeRequired</font> to fire with the value of the <font face="Courier New" size="2">ZipCode</font> property</p>
<p>3) How do I initiate this on <font face="Courier New" size="2">userService.Update()</font>?</p>
<p>Let’s take a look at building up the validators.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ValidZipCodeRequiredAttribute : ValidatorAttribute
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> IValidator CreateValidator(IValidatorFactory factory)
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> factory.Create&lt;ValidZipCodeRequiredValidator&gt;();
    }
}</pre>
<p>This allows me to make a <font face="Courier New" size="2">UnityValidatorFactory</font> that can supply all my dependencies. Now how about this business of running the <font face="Courier New" size="2">ValidZipCodeRequiredValidator</font> with the value of the <font face="Courier New" size="2">ZipCode</font> property? For that I made a composite validator that loops through each property and runs the annotated validator against it’s property value.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> CompositeValidator&lt;T&gt; : IValidator&lt;T&gt;
{
    <span class="kwrd">private</span> IValidatorFactory factory;

    <span class="kwrd">public</span> CompositeValidator(IValidatorFactory factory)
    {
        <span class="kwrd">this</span>.factory = factory;
    }

    <span class="kwrd">public</span> IEnumerable&lt;RuleException&gt; Validate(T subject)
    {
        List&lt;RuleException&gt; exceptions = <span class="kwrd">new</span> List&lt;RuleException&gt;();

        <span class="kwrd">foreach</span> (PropertyInfo property <span class="kwrd">in</span> <span class="kwrd">typeof</span>(T).GetProperties())
        {
            <span class="kwrd">foreach</span> (var validator <span class="kwrd">in</span> GetValidatorsFor(property))
            {
                exceptions.AddRange(validator.Validate(property.GetValue(subject, <span class="kwrd">null</span>)));
            }
        }

        <span class="kwrd">return</span> exceptions;
    }

    <span class="kwrd">private</span> IEnumerable&lt;IValidator&gt; GetValidatorsFor(ICustomAttributeProvider provider)
    {
        <span class="kwrd">foreach</span> (ValidatorAttribute attribute
            <span class="kwrd">in</span> provider.GetCustomAttributes(<span class="kwrd">typeof</span>(ValidatorAttribute), <span class="kwrd">true</span>))
        {
            <span class="kwrd">yield</span> <span class="kwrd">return</span> attribute.CreateValidator(factory);
        }
    }
}</pre>
<p>Now I just need to run the <font face="Courier New" size="2">CompositeValidator</font> on <font face="Courier New" size="2">userService.Update()</font>. For that I use Unity Interception:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ValidationCallHandler : ICallHandler
{
    <span class="kwrd">private</span> IValidator validator;

    <span class="kwrd">public</span> ValidationCallHandler(IValidator validator)
    {
        <span class="kwrd">this</span>.validator = validator;
    }

    <span class="kwrd">public</span> IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var ruleExceptions = ValidateEachArgument(input.Arguments);

        <span class="kwrd">if</span> (ruleExceptions.Count() &gt; 0)
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> ValidationException(ruleExceptions);
        }

        <span class="kwrd">return</span> getNext()(input, getNext);
    }

    <span class="kwrd">private</span> IEnumerable&lt;RuleException&gt; ValidateEachArgument(IParameterCollection arguments)
    {
        var ruleExceptions = <span class="kwrd">new</span> List&lt;RuleException&gt;();

        <span class="kwrd">foreach</span> (var arg <span class="kwrd">in</span> arguments)
        {
            ruleExceptions.AddRange(validator.Validate(arg));
        }

        <span class="kwrd">return</span> ruleExceptions;
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Order { get; set; }
}</pre>
<p>Phew, we’re almost done. The only thing left is to apply this validator in configuration so I can keep the Unity reference out of my core domain. That looks like this:</p>
<pre class="csharpcode">container.AddNewExtension&lt;Interception&gt;()
    .Configure&lt;Interception&gt;()
    .SetInterceptorFor&lt;IUserService&gt;(<span class="kwrd">new</span> InterfaceInterceptor())
    .AddPolicy(<span class="str">&quot;UserServiceValidationPolicy&quot;</span>)
    .AddCallHandler&lt;ValidationCallHandler&gt;()
    .AddMatchingRule&lt;AlwaysApplyMatchingRule&gt;();</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/validation-with-unity-interception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Auto-Mocking Unity Container Extension</title>
		<link>http://www.agileatwork.com/auto-mocking-unity-container-extension/</link>
		<comments>http://www.agileatwork.com/auto-mocking-unity-container-extension/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 21:20:58 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=119</guid>
		<description><![CDATA[Using a container for unit testing is a good way to insulate your tests from changes in object construction. Typically my first test will be something pretty boring just to get the process started. A few tests later, the real behavior comes out along with new dependencies. Rather than having to go back and add [...]]]></description>
			<content:encoded><![CDATA[<p>Using a container for unit testing is a good way to insulate your tests from changes in object construction. Typically my first test will be something pretty boring just to get the process started. A few tests later, the real behavior comes out along with new dependencies. Rather than having to go back and add the dependencies to all the tests I’ve already written, I like to use a container to build up the object I’m testing.</p>
<p>To streamline this process, I thought it would be handy to use a container extension to auto generate mocks for any required interface that wasn’t explicitly registered. The best way I can explain this is with code, so here it is:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">[<span style="color: #2b91af">SetUp</span>]</pre>
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> SetUp()</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; container = <span style="color: blue">new</span> <span style="color: #2b91af">UnityContainer</span>()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddNewExtension&lt;<span style="color: #2b91af">AutoMockingContainerExtension</span>&gt;();</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">[<span style="color: #2b91af">Test</span>]</pre>
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> Should_be_really_easy_to_test()</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; container</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .RegisterMock&lt;<span style="color: #2b91af">IDependencyThatNeedsExplicitMocking</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Setup(d =&gt; d.MyMethod(<span style="color: #2b91af">It</span>.IsAny&lt;<span style="color: blue">int</span>&gt;()))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Returns(<span style="color: #a31515">&quot;I want to specify the return value&quot;</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> service = container.Resolve&lt;<span style="color: #2b91af">ServiceWithThreeDependencies</span>&gt;();</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> result = service.DoSomething();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Assert</span>.That(result, <span style="color: #2b91af">Is</span>.EqualTo(<span style="color: #a31515">&quot;I didn't have to mock the other 2 dependencies!&quot;</span>));</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>It really reduces the noise level in tests and lets you focus on the interesting parts of your application. Here’s the code for the container extension:</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="luigi" border="0" alt="luigi" src="http://www.agileatwork.com/wp-content/uploads/2009/06/luigi1.jpg" width="150" height="115" /></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">AutoMockingContainerExtension</span> : <span style="color: #2b91af">UnityContainerExtension</span></pre>
<pre style="margin: 0px">{</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> Initialize()</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> strategy = <span style="color: blue">new</span> <span style="color: #2b91af">AutoMockingBuilderStrategy</span>(Container);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; Context.Strategies.Add(strategy, <span style="color: #2b91af">UnityBuildStage</span>.PreCreation);</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">class</span> <span style="color: #2b91af">AutoMockingBuilderStrategy</span> : <span style="color: #2b91af">BuilderStrategy</span></pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IUnityContainer</span> container;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> AutoMockingBuilderStrategy(<span style="color: #2b91af">IUnityContainer</span> container)</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">this</span>.container = container;</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">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> PreBuildUp(<span style="color: #2b91af">IBuilderContext</span> context)</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> key = context.OriginalBuildKey;</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">if</span> (key.Type.IsInterface &amp;&amp; !container.IsRegistered(key.Type))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; context.Existing = CreateDynamicMock(key.Type);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</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">private</span> <span style="color: blue">static</span> <span style="color: blue">object</span> CreateDynamicMock(<span style="color: #2b91af">Type</span> type)</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> genericMockType = <span style="color: blue">typeof</span>(<span style="color: #2b91af">Mock</span>&lt;&gt;).MakeGenericType(type);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> mock = (<span style="color: #2b91af">Mock</span>)<span style="color: #2b91af">Activator</span>.CreateInstance(genericMockType);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> mock.Object;</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">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>In case you’re wondering about <font size="2" face="Courier New">container.RegisterMock&lt;&gt;</font>, it’s just extension method that you can read about <a href="http://www.agileatwork.com/moq-extension-methods-for-unity/">here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/auto-mocking-unity-container-extension/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Captcha and Inversion of Control</title>
		<link>http://www.agileatwork.com/captcha-and-inversion-of-control/</link>
		<comments>http://www.agileatwork.com/captcha-and-inversion-of-control/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 06:09:18 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=98</guid>
		<description><![CDATA[
I made a few tweaks to a captcha library I found here and basically wrapped their CaptchaImage object in a service interface to use in my application. Pretty easy stuff, but I didn’t get it right the first time.
What’s wrong with this class? (hint: it’s highlighted in yellow)
public class HttpContextCacheCaptchaProvider : ICaptchaProvider
{
    [...]]]></description>
			<content:encoded><![CDATA[<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Inversion of Control" border="0" alt="Inversion of Control" src="http://www.agileatwork.com/wp-content/uploads/2009/06/lorenzoflip.jpg" width="240" height="159" /></p>
<p>I made a few tweaks to a captcha library I found <a href="http://www.codeproject.com/KB/aspnet/CaptchaImage.aspx">here</a> and basically wrapped their <font size="2" face="Courier New">CaptchaImage</font> object in a service interface to use in my application. Pretty easy stuff, but I didn’t get it right the first time.</p>
<p>What’s wrong with this class? <font size="2"><em>(hint: it’s highlighted in yellow)</em></font></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> HttpContextCacheCaptchaProvider : ICaptchaProvider
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> httpContextCacheKey = <span class="str">&quot;4D795A45-8015-475C-A6C4-765B09EB9955&quot;</span>;
    <span class="kwrd">private</span> ICaptchaImageFactory factory;
    <span class="kwrd">private</span> HttpContextBase context;

    <span class="kwrd">public</span> HttpContextCacheCaptchaProvider(ICaptchaImageFactory factory, HttpContextBase context)
    {
        <span class="kwrd">this</span>.factory = factory;
        <span class="kwrd">this</span>.context = context;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        <span style="background: #ffffc0">context.Cache[httpContextCacheKey] = captchaImage.Text;</span>

        <span class="kwrd">using</span> (Bitmap bitmap = captchaImage.RenderImage())
        {
            bitmap.Save(stream, ImageFormat.Jpeg);
        }
    }

    <span class="kwrd">public</span> <span class="kwrd">bool</span> Verify(<span class="kwrd">string</span> text)
    {
        <span style="background: #ffffc0"><span class="kwrd">string</span> captchaText = (<span class="kwrd">string</span>)context.Cache[httpContextCacheKey];</span>

        <span class="kwrd">if</span> (text == <span class="kwrd">null</span> || captchaText == <span class="kwrd">null</span>)
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        <span class="kwrd">else</span>
            <span class="kwrd">return</span> text.ToLower().Equals(captchaText.ToLower());
    }
}</pre>
<p>Perhaps your nose can lead you in the right direction. The smell is <a href="http://c2.com/cgi/wiki?CodeSmellMetrics">hard to test</a>, and it’s hard to test because it requires mocking the <font size="2" face="Courier New">HttpContextBase</font>. You might say “no problem, I can blast out a stub with <a href="http://code.google.com/p/moq/">Moq</a> in no time” but you’re missing the real problem. That would be like taking aspirin for a brain tumor.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="arnold" border="0" alt="arnold" src="http://www.agileatwork.com/wp-content/uploads/2009/06/arnold.jpg" width="208" height="241" /></p>
<blockquote>
<p>It’s not a tumor</p>
</blockquote>
<p>The real problem is this class is violating the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> (SRP) by doing more than one thing. I don’t mean the two methods <font size="2" face="Courier New">Render()</font> and <font size="2" face="Courier New">Verify()</font>, those are a cohesive unit operating on the same data. The other thing is <em>lifetime management</em>. Look how simple the class gets when you invert control and take out the notion of lifetime management:</p>
<pre class="csharpcode">[Serializable]
<span class="kwrd">public</span> <span class="kwrd">class</span> LifetimeManagedCaptchaProvider : ICaptchaProvider
{
    <span class="kwrd">private</span> ICaptchaImageFactory factory;
    <span class="kwrd">private</span> <span class="kwrd">string</span> captchaText;

    <span class="kwrd">public</span> LifetimeManagedCaptchaProvider(ICaptchaImageFactory factory)
    {
        <span class="kwrd">this</span>.factory = factory;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        <span style="background: #ffffc0">captchaText = captchaImage.Text;</span>

        <span class="kwrd">using</span> (Bitmap bitmap = captchaImage.RenderImage())
        {
            bitmap.Save(stream, ImageFormat.Jpeg);
        }
    }

    <span class="kwrd">public</span> <span class="kwrd">bool</span> Verify(<span class="kwrd">string</span> text)
    {
        <span class="kwrd">if</span> (text == <span class="kwrd">null</span> || captchaText == <span class="kwrd">null</span>)
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        <span class="kwrd">else</span>
            <span class="kwrd">return</span> text.ToLower().Equals(captchaText.ToLower());
    }
}</pre>
<p>Now this class is a breeze to test and all you have to do is register it like this:</p>
<pre class="csharpcode">Container.RegisterType&lt;ICaptchaProvider, LifetimeManagedCaptchaProvider&gt;(
    <span class="kwrd">new</span> HttpSessionStateLifetimeManager());</pre>
<p>The moral of the story is let your IoC container do things it’s good at.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/captcha-and-inversion-of-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Unity Container Configuration</title>
		<link>http://www.agileatwork.com/testing-unity-container-configuration/</link>
		<comments>http://www.agileatwork.com/testing-unity-container-configuration/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 05:38:00 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://blog.agileatwork.com/testing-unity-container-configuration/</guid>
		<description><![CDATA[Before Inversion of Control, I would use configuration for a connection string, port number or other boring piece of information. Nowadays however, configuration can be a pretty hairy part of the application in its own right. Not necessarily the xml kind of configuration, just configuration. You know, the place where you use the “new “ [...]]]></description>
			<content:encoded><![CDATA[<p>Before Inversion of Control, I would use configuration for a connection string, port number or other boring piece of information. Nowadays however, configuration can be a pretty hairy part of the application in its own right. Not necessarily the xml kind of configuration, just configuration. You know, the place where you use the “new “ keyword and essentially break all the principals you worked so hard to protect in the rest of your application. Uncle Bob referred to this as “the other side of the wall” in a <a href="http://hanselminutes.com/default.aspx?showID=163">podcast with Scott Hanselman</a>.</p>
<p><a href="http://blog.agileatwork.com/wp-content/uploads/2009/06/afewgoodmenjacktruth1.jpg"><img title="afewgoodmenjacktruth" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin-left: 0px; margin-right: 0px; border-right-width: 0px" height="193" alt="afewgoodmenjacktruth" src="http://blog.agileatwork.com/wp-content/uploads/2009/06/afewgoodmenjacktruth-thumb.jpg" width="188" border="0" /></a></p>
<blockquote style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 10px"><p>“Son, we live in a world that has walls, and those walls have to be guarded by men with guns. Who&#8217;s gonna do it? You? You, Lieutenant Weinberg? I have a greater responsibility than you can possibly fathom…” &#8211; Colonel Nathan R. Jessep</p>
</blockquote>
<div style="clear: both">
<p>In my case, I wanted to inject an encryption provider to do Rijndael encryption with a specific vector and all that. Since I already had another IEncryptionProvider registered with the container, I named the new one.</p>
<pre class="prettyprint">
<code>Container.Configure&lt;InjectedMembers&gt;().ConfigureInjectionFor&lt;RijndaelEncryptionProvider&gt;(
    "MyEncryptionProvider",
    new InjectionConstructor(
        new ResolvedParameter&lt;NoOpSaltStrategy&gt;(),
        new RijndaelConfig { Hash = "SHA1", Vector = "notreal", Iterations = 2, Size = 256 }));

Container.Configure&lt;InjectedMembers&gt;().ConfigureInjectionFor&lt;MyService&gt;(
    new InjectionConstructor(
        new ResolvedParameter&lt;IEncryptionProvider&gt;("MyEncryptionProvider"),
        new ResolvedParameter&lt;DataDropConfigSection&gt;()));        </code></pre>
<p>What is a good way to make sure I’m wiring up Unity properly? I could just go black box and make sure my service can decrypt a string encrypted with a particular vector. That would be pretty BDDish and provide good insulation from volatile configuration code. In this application however, doing a legit integration test was a PITA for other reasons and I wanted some quick feedback on my Unity configuration.</p>
<p>A coworker and I decided to use a container extension to watch all the dependencies that were resolved and then tell us if we got the right one. The unit test looked like this:</p>
<pre class="prettyprint">
<code>[TestFixture]
public class EncryptionProviderTests
{
    private IUnityContainer container;
    private WasResolvedContainerExtension wasResolvedContainerExtension;

    [SetUp]
    public void SetUp()
    {
        wasResolvedContainerExtension = new WasResolvedContainerExtension();

        container = new UnityContainer()
            .AddExtension(wasResolvedContainerExtension)
            .AddNewExtension&lt;WebMvcContainerExtension&gt;();
    }

    [TearDown]
    public void TearDown()
    {
        container.Dispose();
    }

    [Test]
    public void Should_inject_named_instance_of_encryption_provider()
    {
        var service = container.Resolve&lt;MyService&gt;();

        AssertNamedInstanceWasResolved&lt;IEncryptionProvider&gt;("MyEncryptionProvider");
    }

    private void AssertNamedInstanceWasResolved&lt;T&gt;(string name)
    {
        Assert.IsTrue(wasResolvedContainerExtension.WasResolved&lt;T&gt;(name));
    }
}</code>
</pre>
<p>Granted it’s a little magical, but at least it reads well and a failure is pretty easy to track down from that point.&#160; This is what the container extension looks like:</p>
<pre class="prettyprint">
<code>public class WasResolvedContainerExtension : UnityContainerExtension
{
    private WasResolvedBuilderStrategy strategy;

    protected override void Initialize()
    {
        strategy = new WasResolvedBuilderStrategy();

        Context.Strategies.Add(strategy, UnityBuildStage.Creation);
    }

    public bool WasResolved&lt;T&gt;()
    {
        return WasResolved&lt;T&gt;(null);
    }

    public bool WasResolved&lt;T&gt;(string name)
    {
        return strategy.WasResolved&lt;T&gt;(name);
    }
}</code>
</pre>
<p>The real work is done in the BuilderStrategy which looks like:</p>
<pre class="prettyprint">
<code>public class WasResolvedBuilderStrategy : BuilderStrategy
{
    private IList&lt;NamedTypeBuildKey&gt; buildKeys = new List&lt;NamedTypeBuildKey&gt;();

    public override void PreBuildUp(IBuilderContext context)
    {
        buildKeys.Add((NamedTypeBuildKey)context.BuildKey);
    }

    public bool WasResolved&lt;T&gt;()
    {
        return WasResolved&lt;T&gt;(null);
    }

    public bool WasResolved&lt;T&gt;(string name)
    {
        var buildKey = (buildKeys.FirstOrDefault(k =&gt;
        typeof(T).IsAssignableFrom(k.Type) &amp;&amp; k.Name == name));

        return buildKey.Type != null;
    }
}</code>
</pre>
<p>And there you have it, a pretty quick way to test Unity configuration.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/testing-unity-container-configuration/feed/</wfw:commentRss>
		<slash:comments>0</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>

