<?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>Storm in a Jar &#187; .NET Framework</title>
	<atom:link href="http://www.storminajar.net/category/dev/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.storminajar.net</link>
	<description>Grognak&#039;s journal of random ramblings.</description>
	<lastBuildDate>Tue, 13 Dec 2011 12:47:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Supporting multiple databases using the Unit of Work and Repository patterns</title>
		<link>http://www.storminajar.net/2011/12/13/supporting-multiple-databases-using-the-unit-of-work-and-repository-patterns/</link>
		<comments>http://www.storminajar.net/2011/12/13/supporting-multiple-databases-using-the-unit-of-work-and-repository-patterns/#comments</comments>
		<pubDate>Tue, 13 Dec 2011 12:46:26 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Repository]]></category>
		<category><![CDATA[Unit of Work]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1597</guid>
		<description><![CDATA[You might have read my previous entries about the Unit of Work and Repository design patterns. If not, you might want to check them out before reading the rest of this article. Unit of Work &#38; Repository support for multiple frameworks Letting your Unit of Work &#38; Repositories support multiple frameworks A little while ago, [...]]]></description>
			<content:encoded><![CDATA[<p>You might have read my previous entries about the Unit of Work and Repository design patterns. If not, you might want to check them out before reading the rest of this article.</p>
<ul>
<li><a title="Unit of Work &amp; Repository support for multiple frameworks, part 2" href="http://www.storminajar.net/2011/03/13/unit-of-work-repository-support-for-multiple-frameworks-part-2/" target="_blank">Unit of Work &amp; Repository support for multiple frameworks</a></li>
<li><a title="Letting your UnitOfWork &amp; Repositories support multiple frameworks" href="http://www.storminajar.net/2010/08/30/letting-your-unitofwork-repositories-support-multiple-frameworks/" target="_blank">Letting your Unit of Work &amp; Repositories support multiple frameworks</a></li>
</ul>
<p>A little while ago, I had to redesign the Unit of Work and Repository structure in a project at work. Naturally, I was quite happy to do so, as I have done a lot of research and development work on this topic already.</p>
<p><span id="more-1597"></span></p>
<p>A requirement was that the unit of work should be able to work with multiple databases. I figured that the generic approach as described in my previous articles would work just as well to solve this issue. I was rather pleased when I discovered that the sample code, provided as download in one of my previous articles, worked with only a few modifications.</p>
<p>Another thing of beauty &#8211; which is slightly off-topic, but deserves to be mentioned &#8211; was to see the code working through a different <em>inversion of control container</em>. My code always used Castle Windsor for IoC and DI, but the project at work uses StructureMap. I had a little <em>nerdgasm</em> when I saw my code working in a completely different environment; it really gave me the feeling that I had written some very versatile code that can be implemented in different scenarios with very little effort!</p>
<p>On to the actual code now&#8230;</p>
<p>The project uses Entity Framework 4.1 and has no requirements to support different ORM tools. This allowed me to make a few minor code changes to facilitate EF 4.1 a little better.</p>
<p>Let&#8217;s start with the unit of work interface:</p>
<pre class="brush:csharp">
public interface IUnitOfWork : IDisposable
{
    void Commit();
}

/// &lt;summary&gt;
/// Generic unit of work interface for different DbContext objects.
/// &lt;/summary&gt;
/// &lt;remarks&gt;
/// Keyword "out" is specified for the generic parameter
/// to allow casting (covariance).
/// &lt;/remarks&gt;
/// &lt;typeparam name="TContext"&gt;Concrete DbContext type.&lt;/typeparam&gt;
public interface IUnitOfWork&lt;out TContext&gt; : IUnitOfWork
   where TContext : DbContext
{
    TContext Context { get; }
}
</pre>
<p>Very little changes in the code here. An out-keyword was added to the generic TContext parameter and an added restriction that TContext should always be of type DbContext (Entity Framework 4.1 specific change).</p>
<p>The only other change was done in the abstract Repository class:</p>
<pre class="brush:csharp">
public abstract class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt;
    where TEntity : class
{
    private IUnitOfWork&lt;DbContext&gt; unitOfWork;
    private readonly IDbSet&lt;TEntity&gt; entitySet;

    /// &lt;summary&gt;
    /// Creates a new repository.
    /// &lt;/summary&gt;
    /// &lt;param name="unitOfWork"&gt;The unit of work to use.&lt;/param&gt;
    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = (IUnitOfWork&lt;DbContext&gt;)unitOfWork;
        this.entitySet = this.unitOfWork.Context.Set&lt;TEntity&gt;();
    }
}
</pre>
<p>This code was modified to be able to cast the IUnitOfWork to an IUnitOfWork&lt;DbContext&gt;. This is another change specific for EF 4.1 to allow me to access the context and create an entity set.</p>
<p>And finally, the StructureMap registries tie everything together when bootstrapping the application:</p>
<pre class="brush:csharp">
    ForConcreteType&lt;ConcreteContext&gt;();

    ForConcreteType&lt;AnotherConcreteContext&gt;();

    ForConcreteType&lt;UnitOfWork&lt;ConcreteContext&gt;&gt;()
        .Configure
        .Ctor&lt;ConcreteContext&gt;();

    ForConcreteType&lt;UnitOfWork&lt;AnotherConcreteContext&gt;&gt;()
        .Configure
        .Ctor&lt;AnotherConcreteContext&gt;();

    For&lt;ISomeRepository&gt;()
        .Use&lt;SomeRepository&gt;()
        .Ctor&lt;IUnitOfWork&gt;()
        .Is&lt;UnitOfWork&lt;ConcreteContext&gt;&gt;();

    For&lt;IOtherRepository&gt;()
        .Use&lt;OtherRepository&gt;()
        .Ctor&lt;IUnitOfWork&gt;()
        .Is&lt;UnitOfWork&lt;AnotherConcreteContext&gt;&gt;();
</pre>
<p>I&#8217;m not an expert on StructureMap, so I&#8217;m not sure if this is the most efficient way to go, but here I define the concrete context objects for the databases as well as which context to use when initializing the repositories.</p>
<p>Hopefully this, combined with my previous posts, is enough to let you figure out the total picture on your own. If there actually is demand for another sample project, let me know in the comments and I&#8217;ll see if I can free up some time to make one.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/12/13/supporting-multiple-databases-using-the-unit-of-work-and-repository-patterns/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rediscovering Telerik</title>
		<link>http://www.storminajar.net/2011/08/22/rediscovering-telerik/</link>
		<comments>http://www.storminajar.net/2011/08/22/rediscovering-telerik/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 08:26:37 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Telerik]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1448</guid>
		<description><![CDATA[I&#8217;ve recently switched to a new employer and only now I realize how much I loved working with the Telerik&#8216;s product suite. I no longer have access to all the goodies Telerik offers. My previous two employers had licenses for either the Ultimate Collection for .NET or just the ASP.NET AJAX components. That&#8217;s roughly five [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently switched to a new employer and only now I realize how much I loved working with the <a href="http://www.telerik.com" target="_blank">Telerik</a>&#8216;s product suite. I no longer have access to all the goodies Telerik offers. My previous two employers had licenses for either the Ultimate Collection for .NET or just the ASP.NET AJAX components. That&#8217;s roughly five to six years of developing in .NET, with Telerik components! Trust me, it&#8217;s rather unpleasant having to revert back to default controls!</p>
<p>From this point of view I looked at Telerik again. What can they still offer me at this point, since I can&#8217;t afford to buy any licenses. In fact, I was pleasantly surprised! I knew they had some free tools, but I never quite realized which. I already knew of <a href="http://www.telerik.com/products/decompiler.aspx" target="_blank">JustDecompile</a> and the <a href="http://www.telerik.com/products/aspnet-mvc.aspx" target="_blank">ASP.NET MVC components</a>. To my delight, I discovered a free version of <a href="http://www.telerik.com/products/orm/free.aspx" target="_blank">OpenAccess ORM</a>! I will admit that this severely limits the toolbox that I got used to, but it&#8217;s still a pretty awesome toolbox to use.</p>
<p><span id="more-1448"></span>A free version of OpenAccess is just a godsend! Due to previously bad experiences with Entity Framework, I didn&#8217;t want to go back to using that. Nor did I want to continue using NHibernate, even though it can do everything I can possibly think of&#8230; it&#8217;s always a pain in the backside to actually get it done. Sure, OpenAccess has it&#8217;s quirks and limitations, but at least there&#8217;s a company supporting their product actively and let&#8217;s not forget about the community contributions!</p>
<p>I don&#8217;t have much experience developing with the <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC framework</a>, but knowing that Telerik&#8217;s controls are free to use might make me look into this option. I quite like the looks of MVC3 with the Razor view engine; it&#8217;s lifted a few of my main objections to working with the MVC framework. So, again&#8230; here I have an opportunity to continue to build applications with the help of an awesome control suite.</p>
<p>In fact, not having access to all the goodies that I&#8217;ve used for all these years might make me a better developer! I&#8217;m forced to reconsider my options and perhaps learn new techniques and start using those.</p>
<p>My thanks to the Telerik team: you&#8217;re not just pushing yourselves with every release, but pushing me as well to stay on top of my game! Continue the awesome work!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/08/22/rediscovering-telerik/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit of Work &amp; Repository support for multiple frameworks, part 2</title>
		<link>http://www.storminajar.net/2011/03/13/unit-of-work-repository-support-for-multiple-frameworks-part-2/</link>
		<comments>http://www.storminajar.net/2011/03/13/unit-of-work-repository-support-for-multiple-frameworks-part-2/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 11:12:40 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Repository]]></category>
		<category><![CDATA[Unit of Work]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1246</guid>
		<description><![CDATA[Quite a while ago I made a post about creating a unit of work and a repository that would allow me to swap between Entity Framework and NHibernate relatively quickly. In the past few weeks (or have they turned into months already?!), I received a few requests for a sample project to show how this can [...]]]></description>
			<content:encoded><![CDATA[<p>Quite a while ago I made a <a title="Letting your UnitOfWork &amp; Repositories support multiple frameworks" href="http://www.storminajar.net/2010/08/30/letting-your-unitofwork-repositories-support-multiple-frameworks/">post</a> about creating a <em>unit of work</em> and a <em>repository </em>that would allow me to swap between <em>Entity Framework </em>and <em>NHibernate</em> relatively quickly. In the past few weeks (or have they turned into months already?!), I received a few requests for a sample project to show how this can be implemented and used in a real world scenario. I sat down to work on it this weekend and I&#8217;m happy to say I managed to finish a working sample project.</p>
<p><a href="http://www.storminajar.net/wp-content/uploads/2011/03/MultiRepository.zip">Click here to download the sample project</a>.</p>
<p>Keep in mind that I won&#8217;t take responsibility for any of this code if you decide to deploy it in a production environment. However, feel free to use this code for your own projects and modify it to suit your own needs. It&#8217;s only meant to provide a sample and show a way how to implement repositories that are not dependant on a specific type of framework.</p>
<p>I truly hope my efforts are appreciated and that it can be a learning experience for everyone who requested a sample project on this issue!</p>
<p><span id="more-1246"></span></p>
<p>Everything you need should be included in the package.</p>
<p><strong>Binaries</strong></p>
<ol>
<li><a href="http://www.castleproject.org/">Castle Windsor</a> 2.5.2<br />
Inversion of Control and Dependency Injection container.</li>
<li><a href="http://nhforge.org/">NHibernate</a> 3.1.0<br />
ORM framework based on the famous Hibernate for Java.</li>
</ol>
<p><strong>Documentation</strong></p>
<ol>
<li>Read Me (How To).docx<br />
Explains how to get started with the sample project and what needs to be done to switch between <em>Entity Framework </em>and <em>NHibernate<br />
</em></li>
<li>Technical documentation.docx<br />
It&#8217;s not really technical documentation as such. Just a few points to note. I haven&#8217;t been able to find the time to sit down and properly document things. I will do so if it proves to be necessary, but I think things are easy enough to understand for the average smart developer!</li>
</ol>
<p><strong>Source</strong></p>
<p><strong></strong>All projects and source-code can be seen by opening up the <em>MultiRepository</em> solution file.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/03/13/unit-of-work-repository-support-for-multiple-frameworks-part-2/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>NHibernate: Association references unmapped class</title>
		<link>http://www.storminajar.net/2011/03/07/association-references-unmapped-class/</link>
		<comments>http://www.storminajar.net/2011/03/07/association-references-unmapped-class/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 13:30:06 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1224</guid>
		<description><![CDATA[If this exception message pops up when using NHibernate, make sure to check the following: The mapping file is set as embedded resource; The name of the mapping file ends with .hbm.xml instead of .xml; I just spent two days wondering why this message kept occurring. Turns out that I had named my mapping file: [...]]]></description>
			<content:encoded><![CDATA[<p>If this exception message pops up when using NHibernate, make sure to check the following:</p>
<ul>
<li>The mapping file is set as <em>embedded resource;</em></li>
<li>The name of the mapping file ends with <em>.hbm.xml</em> instead of <em>.xml;</em></li>
</ul>
<p>I just spent two days wondering why this message kept occurring. Turns out that I had named my mapping file: <em>SomeMapping.xml</em>, instead of <em>SomeMapping<strong>.hbm.xml</strong></em>.</p>
<p>Wouldn&#8217;t it be nice to have compile time checks on NHibernate mappings?! Wait&#8230; there is! It&#8217;s called <a title="Fluent NHibernate" href="http://fluentnhibernate.org/" target="_blank">Fluent NHibernate</a> and we don&#8217;t use it here at work. <em>ARGH!</em> Perhaps I should see if I can spend a little time investigating how much effort it is to rewrite all the mappings using Fluent&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/03/07/association-references-unmapped-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate mappings</title>
		<link>http://www.storminajar.net/2011/03/03/nhibernate-mappings/</link>
		<comments>http://www.storminajar.net/2011/03/03/nhibernate-mappings/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 15:27:00 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1212</guid>
		<description><![CDATA[I genuinely hate them! If someone knows a decent graphical editor similar to Entity Framework&#8217;s designer, please let me know!]]></description>
			<content:encoded><![CDATA[<p>I genuinely hate them! If someone knows a decent graphical editor similar to Entity Framework&#8217;s designer, please let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/03/03/nhibernate-mappings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The magic of Castle Windsor!</title>
		<link>http://www.storminajar.net/2011/02/24/the-magic-of-castle-windsor/</link>
		<comments>http://www.storminajar.net/2011/02/24/the-magic-of-castle-windsor/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 11:36:04 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1100</guid>
		<description><![CDATA[A while ago I wrote a few articles on this site about exposing Castle Windsor to your application. For some reason that caught the attention of Krzysztof Koźmic and Mark Seemann. In short they felt I was doing it all wrong! Which led to a follow up article. Fair enough, I was new to the whole principle [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I wrote a few articles on this site about <a title="Castle Windsor: exposing a container to an application" href="http://www.storminajar.net/2010/09/28/castle-windsor-exposing-a-container-to-an-application/">exposing Castle Windsor</a> to your application. For some reason that caught the attention of <a id="commentauthor-56" href="http://kozmic.pl/" rel="external nofollow">Krzysztof Koźmic</a> and <a id="commentauthor-59" href="http://blog.ploeh.dk/" rel="external nofollow">Mark Seemann</a>. In short they felt I was doing it all wrong! Which led to a <a title="Castle Windsor: exposing the container? “Not, at all”" href="http://www.storminajar.net/2010/09/29/castle-windsor-exposing-the-container-not-at-all/">follow up article</a>. Fair enough, I was new to the whole principle of <em>Inversion of Control</em> and <em>Dependency Injection</em>, so I assumed they were in the know and were probably correct in&#8230; correcting me!</p>
<p>Since then I&#8217;ve been fiddling around with it in my spare time, trying to set up an architecture that would allow me to use <em>Castle Windsor</em> as it was intended. Unfortunately, my spare time is a little limited, so it took me a few months in total to come up with something a little more structured and streamlined. However, this week I got to the point where I said to myself: &#8220;Wow, now that&#8217;s cool!&#8221;</p>
<p>I&#8217;m not quite sure where to start. Perhaps it&#8217;s best to give some background information first.</p>
<p>I was looking for a clean solution to implement a <em>Model View Presenter</em> architecture in my application. Ideally this would be coded into a framework that I could use for any other project in the future. In fact, I already <a title="Creating modular web applications" href="http://www.storminajar.net/2010/04/28/creating-modular-web-applications/">posted</a> about modular web applications back in April last year! It addressed the <em>Composite Web Application Block</em> that provided the solution that I was looking for. After playing around with it however, I found it was very cumbersome to work with. Although, with the power of hindsight, that could have been due to my lack of knowledge of <em>IoC </em> and <em>DI</em>.</p>
<p><span id="more-1100"></span>I ended up building my own framework, heavily inspired by the ideas behind the <em>Composite Web Application Block</em>. At first I managed to get along just fine without any form of inversion of control or dependency injection. The further I got down the road, the more obvious it became that, while possible, the code became cluttered and no longer felt as clean as I wanted. At this point we decided in the office to continue down the road of using as little inversion of control and dependency injection as we could get away with. However, in my spare time I decided to research at home how to utilise the capabilities of <em>Castle Windsor</em> to achieve that clean, loosely coupled design that would make my life so easy!</p>
<p>It took a bit of experimenting, but I&#8217;m glad I&#8217;ve done so. I feel I have a much better understanding of the principles of <em>Inversion of Control</em> and <em>Dependency Injection</em> as well as how to use <em>Castle Windsor</em> to help me implement this.</p>
<p>Now that I&#8217;ve given a little introduction to the background information, it&#8217;s time to look at a little class diagram. I&#8217;ve simplified it for the sake of example. It clearly shows five distinctly separate &#8216;layers&#8217;.</p>
<p style="text-align: center;"><a href="http://www.storminajar.net/wp-content/uploads/2011/02/MvpcClassDiagram.jpg" rel="lightbox[1100]"><img class="aligncenter size-large wp-image-1106" title="Simplified MVP Class diagram including Repository and UnitOfWork." src="http://www.storminajar.net/wp-content/uploads/2011/02/MvpcClassDiagram-1024x274.jpg" alt="" width="664" height="178" /></a><em>(Click to enlarge)</em></p>
<p style="text-align: left;">Let&#8217;s quickly go over the things you see in this diagram.</p>
<ul>
<li>Unit of work;<br />
This can be an NHibernate Session or an Entity Framework ObjectContext.</li>
<li>Repository&lt;T&gt;;<br />
The repositories do all the work of querying the context and return objects with data.</li>
<li>Controller;<br />
The controller communicates with repositories and performs validations if needed. The reason for adding a controller is to allow for extending the architecture with <em>web services</em> later. A web service doesn&#8217;t know anything about presenters and views and is only interested in data and validations.</li>
<li>Presenter;<br />
The presenter asks the controller to perform a task and prepares the data for the view.</li>
<li>View;<br />
The view presents the data on the screen (can be a web form, win form, etc).</li>
</ul>
<p>This is the point where <em>Castle Windsor </em>starts to come in.</p>
<p>As the name suggests, <em>WebFormView</em> is a web form. Within <em>Visual Studio</em> you&#8217;d see it as <em>WebFormView.aspx</em> in the <em>Solution Explorer</em>. It&#8217;s just a normal web page. The only thing that differs from &#8220;normal&#8221; is that the code-behind implements the <em>IView</em> interface. The rest of the system is tied together by using one of the most fundamental principles of <em>object oriented programming: <span style="text-decoration: underline;">composition</span></em>.</p>
<p>All I need to do now is to tell <em>Castle Windsor</em> which concrete implementations should be injected in all those classes. This is done through configuration. My personal preference is using XML files to configure, but feel free to use whichever method you prefer. For example:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;components&gt;
    &lt;!-- entity framework object context --&gt;
    &lt;component
      id="context.ef4"
      type="WebClient.Data.ClientModelContainer, WebClient"
      lifestyle="PerWebRequest"&gt;
    &lt;/component&gt;

    &lt;!-- unit of work --&gt;
    &lt;component
      id="unitofwork.ef4"
      service="WebClient.UnitOfWork.IUnitOfWork, WebClient"
      type="WebClient.UnitOfWork.EFUnitOfWork, WebClient"
      lifestyle="PerWebRequest"&gt;
      &lt;parameters&gt;
        &lt;context&gt;${context.ef4}&lt;/context&gt;
      &lt;/parameters&gt;
    &lt;/component&gt;

    &lt;!-- repositories --&gt;
    &lt;component
      id="repositories.defaultdummy"
      service="WebClient.Repositories.IRepository, WebClient"
      type="WebClient.Repositories.DefaultDummyRepository, WebClient"
      lifestyle="PerWebRequest"&gt;
      &lt;parameters&gt;
        &lt;unitOfWork&gt;${unitofwork.ef4}&lt;/unitOfWork&gt;
      &lt;/parameters&gt;
    &lt;/component&gt;
    &lt;component
      id="repositories.otherdummy"
      service="WebClient.Repositories.IRepository, WebClient"
      type="WebClient.Repositories.OtherDummyRepository, WebClient"
      lifestyle="PerWebRequest"&gt;
      &lt;parameters&gt;
        &lt;unitOfWork&gt;${unitofwork.ef4}&lt;/unitOfWork&gt;
      &lt;/parameters&gt;
    &lt;/component&gt;

    &lt;!-- controllers --&gt;
    &lt;component
      id="controllers.default"
      service="WebClient.Controllers.IController, WebClient"
      type="WebClient.Controllers.DefaultController, WebClient"
      lifestyle="PerWebRequest"&gt;
      &lt;parameters&gt;
        &lt;repositories&gt;
          &lt;array&gt;
            &lt;repository&gt;${repositories.defaultdummy}&lt;/repository&gt;
            &lt;repository&gt;${repositories.otherdummy}&lt;/repository&gt;
          &lt;/array&gt;
        &lt;/repositories&gt;

      &lt;/parameters&gt;
    &lt;/component&gt;

    &lt;!-- presenters --&gt;
    &lt;component
      id="presenters.default"
      service="WebClient.Presenters.IPresenter, WebClient"
      type="WebClient.Presenters.DefaultPresenter, WebClient"
      lifestyle="PerWebRequest"&gt;
      &lt;parameters&gt;
        &lt;controller&gt;${controllers.default}&lt;/controller&gt;
      &lt;/parameters&gt;
    &lt;/component&gt;
  &lt;/components&gt;
&lt;/configuration&gt;</pre>
<p>If you have studied the XML configuration for a moment, you will notice that I am not specifying a v<em>iew </em>parameter in the configuration for the p<em>resenter</em> component. However, the class diagram clearly shows we need to have a view! This is because it will be detected dynamically on run-time which view needs to be given as a parameter.</p>
<p>I can feel you already wondering how this works. But, before I can tell you, I will have to add a few more tidbits of information to glue everything together.</p>
<p>The view is the absolute starting point. When sending a request to the server to load <em>WebFormView.aspx  <em> </em>(or any other web page), </em>I need to figure out which presenter to resolve. To prevent having to write the same code on each and every page, I&#8217;ve adopted a naming convention strategy that allows me to figure this out &#8220;on the fly&#8221; in a <em>base page class</em>:</p>
<blockquote><p>The Id of the component within the <em>Castle Windsor </em>configuration should be able to be deducted from the root application path<em> </em>of the web page that has been requested.</p></blockquote>
<p>Here&#8217;s a few examples to show what I mean:</p>
<p>url: http://localhost/default.aspx<br />
id: presenters.default</p>
<p>url: http://localhost/subfolder/default.aspx<br />
id: presenters.subfolder.default</p>
<p>url: http://localhost/MyAppRoot/default.aspx<br />
id: presenters.default</p>
<p>url: http://localhost/MyAppRoot/subfolder/default.aspx<br />
id: presenters.subfolder.default</p>
<p>Once I figured out that I could resolve presenters based on a naming convention, the code was pretty easy to write:</p>
<pre class="brush:csharp">public class Page : System.Web.UI.Page, IView
{
    protected IPresenter presenter;

    /// &lt;summary&gt;
    /// Initializes the page. In this case it resolves our presenter class
    /// through Castle Windsor.
    /// &lt;/summary&gt;
    /// &lt;param name="sender"&gt;&lt;/param&gt;
    /// &lt;param name="e"&gt;&lt;/param&gt;
    protected virtual void Page_Init(object sender, EventArgs e)
    {
        string windsorKey = "";

        try
        {
            // Determine which presenter to resolve.
            int rootPathIndex = Request.Path.IndexOf(Request.ApplicationPath);
            int dotAspxIndex = Request.Path.IndexOf(".aspx");

            windsorKey = Request.Path
                .Remove(dotAspxIndex, 5)                                // strip .aspx
                .Remove(rootPathIndex, Request.ApplicationPath.Length)  // strip the root
                .Replace("/", ".")                                      // replace slash
                .ToLower();                                             // to lowercase

            // Finally create the proper windsor key.
            windsorKey = (windsorKey.StartsWith("."))
                ? String.Format("presenters{0}", windsorKey)
                : String.Format("presenters.{0}", windsorKey);

            // Let the presenter factory take care of creating the presenter.
            // Castle Windsor will make sure all dependencies will be resolved.
            this.presenter = HttpApplication.PresenterFactory.Create(windsorKey, this);
        }
        catch (Exception ex)
        {
            string message = String.Format(
                "Error trying to resolve presenter: {0}. See InnerException for details",
                windsorKey);

            throw new FrameworkException(message, ex);
        }
    }
}</pre>
<p>Pretty neat, huh? But, wait! There&#8217;s something new in this code! Have you spotted it? I&#8217;ll highlight it for you, just in case:</p>
<pre class="brush:csharp">// Let the presenter factory take care of creating the presenter.
// Castle Windsor will make sure all dependencies will be resolved.
this.presenter = HttpApplication.PresenterFactory.Create(windsorKey, this);</pre>
<p>Up until now I&#8217;ve not spoken about the presenter factory yet. One of the things that I had a truly hard time to understand when trying to figure this out was the so-called <a href="http://stw.castleproject.org/Windsor.Three-Calls-Pattern.ashx">Three Calls Pattern</a>. When I read through that page for the very first time, I got a proper <em>&#8216;what the fuck&#8217; </em>feeling! Once I figured it out, it was actually fairly straight forward. The mistake I made earlier was exposing the container to the application to resolve objects. In fact, if the system is designed properly, I found I don&#8217;t really need access to the container at all.</p>
<p>In short it means: make sure to call<em> Install()</em> on the container just once when the application starts, resolve one object that resolves <em>everything else </em>through dependency injection (hint: remember how the XML configuration looks) and finally release the object to free up memory. In my own situation it means that I install the container and resolve the <em>PresenterFactory</em> during <em>Application_Start</em> in the <em>HttpApplication</em> of my framework.</p>
<pre class="brush:csharp">public class HttpApplication : System.Web.HttpApplication
{
    public static IPresenterFactory PresenterFactory;

    protected virtual void Application_Start(object sender, EventArgs e)
    {
        // Retrieve modules from (web) application configuration.
        ModuleSection moduleConfigSection = (ModuleSection)
            ConfigurationManager.GetSection("moduleSettings/modules");

        if (moduleConfigSection == null)
        {
            // Config secion not found, throw detailed exception message.
            throw new FrameworkException(
                "Please add module configuration to the application configuration "
                + "file: \n\r\n\r"
                + "&lt;sectionGroup name=\"moduleSettings\"&gt;\n\r"
                + "     &lt;section \n\r"
                + "         name=\"modules\" \n\r"
                + "         type=\"Framework.Configuration.ModuleSection, "
                + "                   Framework\" \n\r"
                + "         allowDefinition=\"Everywhere\" \n\r"
                + "         allowLocation=\"true\"/&gt;\n\r"
                + "&lt;/sectionGroup&gt;"
            );
        }

        // Initialize the required/ specified modules.
        ModuleInitializer.Initialize(moduleConfigSection.Modules);

        // Module initialization will have registered all necessary
        // windsor components, it should be safe to call Install()
        Windsor.Install();

        // Windsor installed, resolve the presenter factory.
        PresenterFactory = Windsor.Resolve&lt;IPresenterFactory&gt;();
    }
}</pre>
<p><em>Castle Windsor</em> has a feature called <em>typed factory facilities</em>. This is actually pretty cool. I can use this to create a <em>PresenterFactory</em> interface through which I can resolve a presenter. <em>Castle Windsor</em> is smart enough to figure out all the nitty gritty details for me. I only specify the interface and tell the configuration to use the typed facility factory and <em>that&#8217;s it</em>!</p>
<pre class="brush:csharp">public interface IPresenterFactory
{
    IPresenter Create(string name, IView view);
}</pre>
<p>To create a presenter, I need to specify two parameters: the name of the presenter to resolve and the view object to inject. This is exactly what you saw me do earlier, when calling the <em>PresenterFactory</em> from the <em>Page_Init</em>! However, there is a small downside&#8230; this doesn&#8217;t work out of the box. <em>Castle Windsor </em>will have to understand these parameters. This can be done by writing a c<em>ustom component selector</em>:</p>
<pre class="brush:csharp">public class PresenterTypedFactoryComponentSelector : DefaultTypedFactoryComponentSelector
{
    protected override string GetComponentName(MethodInfo method, object[] arguments)
    {
        if (method.Name == "Create"
            &amp;&amp; arguments.Length == 2
            &amp;&amp; arguments[0] is string)
        {
            return (string)arguments[0];
        }

        return base.GetComponentName(method, arguments);
    }
}</pre>
<p>It looks a little intimidating, but all this does is override Windsor&#8217;s method to get the component. It checks if the calling method name equals <em>Create</em> and if the method was called using two parameters and the first parameter needs to be a string. I could have done some additional checks, such as checking if the second parameter is of the type <em>IView</em>, but I didn&#8217;t think this was too big of an issue.</p>
<p>Now that all the missing pieces have been assembled, it&#8217;s time to let <em>Castle Windsor</em> know that we&#8217;d like to use a <em>typed factory facility</em> with our own home-made <em>custom component selector.</em> Simply open up the configuration file and insert at the top:</p>
<pre class="brush:xml">&lt;!-- typed factory facilities --&gt;
&lt;facilities&gt;
  &lt;facility
    id="facilities.typedfactory"
    type="Castle.Facilities.TypedFactory.TypedFactoryFacility, Castle.Windsor"&gt;
    &lt;factories&gt;
      &lt;factory
        id="facilities.typedfactory.presenters"
        interface="WebClient.IPresenterFactory, WebClient"
        selector="${components.selectors.presenter}" /&gt;
    &lt;/factories&gt;
  &lt;/facility&gt;
&lt;/facilities&gt;

&lt;components&gt;
  &lt;!-- custom selectors --&gt;
  &lt;component
    id="components.selectors.presenter"
    service="Castle.Facilities.TypedFactory.ITypedFactoryComponentSelector, Castle.Windsor"
    type="WebClient.PresenterTypedFactoryComponentSelector, WebClient"&gt;
  &lt;/component&gt;
&lt;/components&gt;</pre>
<p>At this point everything is done! Let me summarize what I&#8217;ve achieved with all this code and configuration:</p>
<p>Using the Three Calls Pattern to automatically resolve a presenter through the <em>PresenterFactory</em> by looking at the URL of the requested web page. Not only the presenter is resolved, its controllers, repositories and unit of work are automatically resolved and injected. Even better, the unit of work has a parameter to resolve the object context of the entity framework! There&#8217;s never a need to look back to instantiate things myself (slight detail: remember to implement <em>IDisposable</em> in the unit of work to dispose of the context when the unit of work gets disposed)!</p>
<p>Let&#8217;s see if we can sum up the advantages of using this approach:</p>
<ul>
<li>Flexible due to configuration;</li>
<li>Easy to add new functionalities because the system is <em>loosely coupled </em>and isn&#8217;t dependant on <em>concrete implementations</em>;</li>
<li>Allows the use of the MVP design pattern to create a web forms application;</li>
<li>Allows for injecting mock classes to help unit testing;</li>
</ul>
<p>I can easily see that one of the biggest disadvantages of this approach is that it might be hard to understand for developers who aren&#8217;t familiar yet with <em>inversion of control</em> and <em>dependency injection</em> and who have never worked with IoC containers such as <em>Castle Windsor.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/02/24/the-magic-of-castle-windsor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stylesheets, stylesheets, stylesheets&#8230; ARGH!</title>
		<link>http://www.storminajar.net/2011/01/19/stylesheets-stylesheets-stylesheets-argh/</link>
		<comments>http://www.storminajar.net/2011/01/19/stylesheets-stylesheets-stylesheets-argh/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 10:16:14 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Telerik]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=1094</guid>
		<description><![CDATA[Ever had a problem in your code where you ended up banging your head against a brick wall for a number of days? To make it better, once solved the solution appeared to be so laughably easy that it&#8217;s kind of embarrassing to explain why it took you so long to notice the mistake? Of [...]]]></description>
			<content:encoded><![CDATA[<p>Ever had a problem in your code where you ended up banging your head against a brick wall for a number of days? To make it better, once solved the solution appeared to be so laughably easy that it&#8217;s kind of embarrassing to explain why it took you so long to notice the mistake? Of course you have! Every developer has moments like that. Everyone denying this is a big, fat liar! Today&#8217;s post will be about my own little&#8230; problem.</p>
<p>I was trying to add a <em>stylesheet</em> to the <em>RadStyleSheetManager</em> during an <em>AJAX-postback</em>. Sounds pretty easy, right? That&#8217;s what I thought too&#8230; Wrong! Or, as it turns out, it was after all.</p>
<p>I had a custom<em> UserControl</em> that includes a stylesheet during the <em>OnInit</em> event. So far, so good. I had even seen it work on another page within the project. When I tried to use the same <em>UserControl</em> on a different page, it looked as if the included styles didn&#8217;t get picked up. The control itself was working fine and displaying all data, except it seemed to be missing all the mark-up. That <em>must </em>automatically mean the stylesheet didn&#8217;t get included, right? Right?!</p>
<p>Turns out that the whole problem was that the HTML on the <em>UserControl</em> used classes that were specified in a different stylesheet than the one being included on the <em>OnInit </em>event! Yeah, that should have been one of the first things to check when I discovered it wasn&#8217;t working on my page, but was working properly on another. However, for some reason I didn&#8217;t check and ended up being a bit frustrated with what seemed an illogical problem while, in fact, it wasn&#8217;t a problem at all. Just stupidity on my part.</p>
<p>To make things even more hilarious, I had created a support ticket at Telerik. In the ticket I had included a sample project so that the folks at Telerik Support would easily be able to reproduce my problem and help me out. Unwittingly I had created a class library project called &#8220;External&#8221; and included the stylesheet in there as an <em>embedded resource. </em>I had quickly tested my sample project and being satisfied that the problem was being reproduced, I attached it to the support ticket.</p>
<p>The response to the ticket was, to me, very surprising. Apparently there is a bug in the current Telerik release that causes a problem where stylesheets are not picked up from an assembly called &#8216;External&#8217;. External is a reserved keyword and due to a little error in Telerik&#8217;s software, the stylesheet didn&#8217;t get picked up from the assembly. I even got awarded 500 Telerik points for reporting a bug in their software! <em><strong>Awesome!</strong></em></p>
<p>However, it got me thinking&#8230; the project that originally caused this problem for me didn&#8217;t have any assemblies called &#8216;External&#8217;. How come I&#8217;m having this problem then? I started digging around and that&#8217;s when I found out I had included the <em>other </em>stylesheet. Oops! Pretty embarrassing, right? I do feel a little better for having contributed, albeit unwittingly and in a very tiny way, to improving the quality of the Telerik components!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2011/01/19/stylesheets-stylesheets-stylesheets-argh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Castle Windsor: exposing the container? &#8220;Not, at all&#8221;</title>
		<link>http://www.storminajar.net/2010/09/29/castle-windsor-exposing-the-container-not-at-all/</link>
		<comments>http://www.storminajar.net/2010/09/29/castle-windsor-exposing-the-container-not-at-all/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 07:36:14 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=931</guid>
		<description><![CDATA[It looks as if yesterday&#8217;s entry about Castle Windsor went all over the Internet. Somehow it also got to the attention of Krzysztof Koźmic. He seems a rather smart fellow, being project leader of Castle Core and Castle DynamicProxy! He made a tweet in reference to my entry: http://bit.ly/aSmqFy “So how do I expose my [...]]]></description>
			<content:encoded><![CDATA[<p>It looks as if yesterday&#8217;s entry about <em>Castle Windsor</em> went all over the Internet. Somehow it also got to the attention of <a href="http://kozmic.pl/" target="_blank">Krzysztof Koźmic</a>. He seems a rather smart fellow, being project leader of <em>Castle Core</em> and <em>Castle DynamicProxy</em>! He made a tweet in reference to my entry:</p>
<blockquote><p><a href="http://bit.ly/aSmqFy">http://bit.ly/aSmqFy</a> “So how do I expose my container to the application?” &lt;&#8211; not, at all</p></blockquote>
<p><em>Very </em>helpful indeed! I will immediately accept that Krzysztof is a lot smarter than I am and that he knows what he&#8217;s on about. As eager as I am to learn new things, I&#8217;m hoping this entry will come to his attention as well. Secretly, I&#8217;m hoping that he will share his wisdom to enlighten the ignorant (aka. myself). If at all possible, in slightly more detail.</p>
<p><span id="more-931"></span>Let&#8217;s start with what I think I know about <em>Castle Windsor. </em>It has a container that, amongst other things, provides <em>Inversion of Control </em> and <em>Depedency Injection. </em>Within the container there are components that can be resolved. If the components have dependencies on other components, <em>Castle Windsor </em>is smart enough to detect and inject them.</p>
<p>From here on things start to get confusing for me. In my ignorance I had assumed that at some point in my application I could give the container a poke to resolve an object for me. I would then use the object for whatever purpose it was created and release it after. If I don&#8217;t expose some way to resolve objects from the container, how the heck am I supposed to get them out of there?</p>
<p>From the <a href="http://stw.castleproject.org/Windsor.Three-Calls-Pattern.ashx" target="_blank">Three Calls Pattern</a> I had assumed that it&#8217;s good practice to install the container at only one point in my application, rather than creating a new container whenever I&#8217;d want an object. This made perfect sense to me. What doesn&#8217;t make sense to me is <em>Call Two</em><span style="text-decoration: underline;">;</span> resolving the root component. Thankfully there was a little notice after that this is not a very strict rule at all and resolve can be called when I have multiple root components.</p>
<p>Imagine the following XML configuration to install the container:</p>
<pre class="brush:xml">&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;components&gt;
    &lt;component id="data.unitofwork"
               service="Services.Data.IUnitOfWork, Services"
               type="Services.Data.UnitOfWork, Services"
               lifestyle="custom"
               customLifestyleType="Framework.Windsor.PerConversationLifeStyleManager"&gt;
    &lt;/component&gt;
    &lt;component id="data.catservice"
               service="Services.ICatService, Services"
               type="Services.CatService, Services"
               lifestyle="Transient"&gt;
    &lt;/component&gt;
    &lt;component id="data.dogservice"
               service="Services.IDogService, Services"
               type="Services.DogService, Services"
               lifestyle="Transient"&gt;
    &lt;/component&gt;
    &lt;component id="data.ownerservice"
               service="Services.IOwnerService, Services"
               type="Services.OwnerService, Services"
               lifestyle="Transient"&gt;
    &lt;/component&gt;
  &lt;/components&gt;
&lt;/configuration&gt;</pre>
<p>Why would I want to resolve any of these objects immediately after installing the container? I want to use these objects at a later stage in my application (e.g. when I actually <em>need</em> them). So again, if I don&#8217;t expose some way to resolve objects from the container, how am I supposed to get one? I see absolutely no point in resolving the objects straight after installation where I simply don&#8217;t need them.</p>
<p>If<em> </em>it is considered bad practice to want to resolve an object on-the-fly whenever and wherever I want, I will freely admit that I&#8217;ve totally missed the point of <em>Castle Windsor </em>and will humbly ask for someone to enlighten me with a practical real-world example of how things &#8220;should&#8221; be done!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/09/29/castle-windsor-exposing-the-container-not-at-all/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Castle Windsor: exposing a container to an application</title>
		<link>http://www.storminajar.net/2010/09/28/castle-windsor-exposing-a-container-to-an-application/</link>
		<comments>http://www.storminajar.net/2010/09/28/castle-windsor-exposing-a-container-to-an-application/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 07:58:49 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Castle Windsor]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=915</guid>
		<description><![CDATA[A while ago I wrote multiple entries about generic factories and repositories. The ObjectFactory I created there was loosely based around the ideas of Inversion of Control. I&#8217;ve learned many new things by now and apparently it&#8217;s a reasonably common journey for anyone new to IoC to start out with a little ObjectFactory class and [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago I wrote <a href="http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/" target="_blank">multiple entries</a> about generic factories and repositories.</p>
<p>The <em>ObjectFactory</em> I created there was loosely based around the ideas of <em>Inversion of Control</em>. I&#8217;ve learned many new things by now and apparently it&#8217;s a reasonably common journey for anyone new to IoC to start out with a little <em>ObjectFactory</em> class and move on towards more advanced <em>Inversion of Control </em>and <em>Dependency Injection</em> containers, such as <a href="http://www.castleproject.org/" target="_blank">Castle Windsor</a>.</p>
<p>Making the transition to Castle Windsor has been a bit of a frustrating one. There&#8217;s plenty of information to find on the Internet, but everywhere I looked it was only the basic sample of registering and resolving objects, using facilities and so on. The frustrating part was that none of the articles I could find dealt with using the <em>IWindsorContainer</em> in a large enterprise architecture.</p>
<p>A very practical question I had almost immediately after toying with the basics was: &#8220;So how do I expose my container to the application?&#8221; I found the <a href="http://stw.castleproject.org/Windsor.Three-Calls-Pattern.ashx" target="_blank">Three Calls Pattern</a> article on the Castle Project Wiki. Not that it is extremely helpful, it&#8217;s good to know how the Windsor developers meant the container to be used. It still didn&#8217;t answer my question though. I was nowhere closer to knowing how to expose my container. A lot of articles simply make the container available through a static property in the <em>Global.asax</em>. I&#8217;m sure this will work splendidly if the only thing I would need to worry about was a single web application project. However, I have an entire framework consisting of multiple class libraries and a client that consists of multiple web application projects and class libraries as well!</p>
<p><span id="more-915"></span>In the end, as is so often the case, the answer was rather simple: use the <em>Singleton</em> design pattern to expose a single container to the entire application.</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using Castle.Core.Resource;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace Storminajar.Framework.Services
{
    public static class WindsorService
    {
        private static bool isInstalled = false;
        private static object locker = new object();
        private static IWindsorContainer container = new WindsorContainer();
        private static IList&lt;IWindsorInstaller&gt; installers =
            new List&lt;IWindsorInstaller&gt;();       

        /// &lt;summary&gt;
        /// Adds installer to the container.
        /// &lt;/summary&gt;
        /// &lt;param name="installer"&gt;&lt;/param&gt;
        public static void AddInstaller(IWindsorInstaller installer)
        {
            lock (locker)
            {
                if (!installers.Contains&lt;IWindsorInstaller&gt;(installer))
                {
                    installers.Add(installer);
                }
            }
        }

        /// &lt;summary&gt;
        /// Adds installer to the container using embedded xml configuration file.
        /// &lt;/summary&gt;
        /// &lt;param name="assembly"&gt;Assembly containing the configuration file.&lt;/param&gt;
        /// &lt;param name="filename"&gt;The name of the configuration file;
        /// path must be included (e.g.: Configuration/Components.xml).&lt;/param&gt;
        public static void AddAssemblyResourceInstaller(string assembly, string filename)
        {
            string assemblyResourcePath =
                String.Format("assembly://{0}/{1}", assembly, filename);

            IWindsorInstaller installer =
                Configuration.FromXml(new AssemblyResource(assemblyResourcePath));

            lock (locker)
            {
                if (!installers.Contains&lt;IWindsorInstaller&gt;(installer))
                {
                    installers.Add(installer);
                }
            }
        }

        /// &lt;summary&gt;
        /// Installs container.
        /// &lt;/summary&gt;
        public static void Install()
        {
            if (!isInstalled)
            {
                if (installers.Count &gt; 0)
                {
                    container.Install(installers.ToArray());
                    isInstalled = true;
                }
                else
                {
                    throw new Exception(
                        "Can not install container: no installers have been added.");
                }
            }
            else
            {
                throw new Exception("Container is already installed! "
                    + "Clear() needs to be called before you can "
                    + "(re)install container.");
            }
        }

        /// &lt;summary&gt;
        /// Clears the container.
        /// &lt;/summary&gt;
        public static void Clear()
        {
            container.Dispose();
            container = new WindsorContainer();
            isInstalled = false;
        }

        /// &lt;summary&gt;
        /// Resolves object from container.
        /// &lt;/summary&gt;
        /// &lt;typeparam name="T"&gt;Type of object to resolve.&lt;/typeparam&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static T Resolve&lt;T&gt;()
        {
            return container.Resolve&lt;T&gt;();
        }

        /// &lt;summary&gt;
        /// Releases object fron container and frees up resources.
        /// &lt;/summary&gt;
        /// &lt;param name="instance"&gt;&lt;/param&gt;
        public static void Release(object instance)
        {
            container.Release(instance);
        }

        /// &lt;summary&gt;
        /// Adds a component to the container.
        /// &lt;/summary&gt;
        /// &lt;typeparam name="T"&gt;Type of object.&lt;/typeparam&gt;
        /// &lt;param name="instance"&gt;The instance of the object to add.&lt;/param&gt;
        public static void Register&lt;T&gt;(T instance)
        {
            container.Register(
                Component.For&lt;T&gt;().Instance(instance));
        }
    }
}</pre>
<p>I have now successfully exposed the <em>IWindsorContainer</em> to my application. When I&#8217;d like to use it to I can simply call any of the methods from anywhere in my code and not worry about a thing!</p>
<p>I will probably write a follow-up later, showing how I used Castle Windsor together with NHibernate conversations and repositories.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/09/28/castle-windsor-exposing-a-container-to-an-application/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Letting your UnitOfWork &amp; Repositories support multiple frameworks</title>
		<link>http://www.storminajar.net/2010/08/30/letting-your-unitofwork-repositories-support-multiple-frameworks/</link>
		<comments>http://www.storminajar.net/2010/08/30/letting-your-unitofwork-repositories-support-multiple-frameworks/#comments</comments>
		<pubDate>Mon, 30 Aug 2010 14:30:20 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Repository]]></category>
		<category><![CDATA[Unit of Work]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=851</guid>
		<description><![CDATA[On popular demand, part 2 with a sample project can be found here. A little while ago I found myself in a situation where I had to replace Microsoft&#8217;s Entity Framework with NHibernate. I had figured this wouldn&#8217;t be too much of a problem! I had neatly used a Unit of Work and Repository implementation [...]]]></description>
			<content:encoded><![CDATA[<p>On popular demand, part 2 with a sample project can be found <a href="http://www.storminajar.net/2011/03/13/unit-of-work-repository-support-for-multiple-frameworks-part-2/">here</a>.</p>
<p>A little while ago I found myself in a situation where I had to replace Microsoft&#8217;s Entity Framework with NHibernate. I had figured this wouldn&#8217;t be too much of a problem! I had neatly used a Unit of Work and Repository implementation for all my data access needs, so I felt pretty secure in the knowledge that I should be able to switch quite quickly between the two.</p>
<p>Eventually I did, it wasn&#8217;t near as quick as I had initially thought though. I discovered that all these articles on the internet describe how to implement a Unit of Work <em>for a single framework!</em> The one I had written was focused solely on the <em>Entity Framework</em> and was pretty much useless for <em>NHibernate</em>. Dismayed, I decided to scrap what I had and start over with the design. This time specifically keeping in mind that I might want to be able to swap between the two at some point in the future.</p>
<p><span id="more-851"></span>Let&#8217;s start at the beginning. To be able to create a common interface for my repositories, and a common way to interact with my repositories, I decided I would need a common UnitOfWork interface as well. It doesn&#8217;t have to do anything, as long as it gives me the ability to cast my objects back and forth.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Doesn't do anything besides providing a common interface.
/// &lt;/summary&gt;
/// &lt;remarks&gt;
/// TODO: Distinguish common functionality later and implement it!
/// &lt;/remarks&gt;
public interface IUnitOfWork : IDisposable
{
}</pre>
<p>Well, that was easy! I now have my interface. I can already picture the frown on your face. After all, what&#8217;s the bloody point of an interface without methods?! Admittedly, not much at first sight. Bear with me and you&#8217;ll find out why I&#8217;ve done this.</p>
<p>The following thing I needed was some sort of interface that allows me to specify the type of context for the Unit of Work. Aha! I smell <em>generics</em>!</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Provides a generic interface for a Unit of Work.
/// &lt;/summary&gt;
public interface IUnitOfWork&lt;TContext&gt; : IUnitOfWork
{
    TContext Context;
    void SaveChanges&lt;TEntity&gt;(TEntity entity);
    void CancelChanges();
}</pre>
<p>Let&#8217;s not worry about the specifics yet. The only thing I am worried about here is providing a <em>generic</em> Unit of Work. This way I can simply define a Unit of Work and give the type of the context along with it, for example the <em>ObjectContext</em> for EF4 and <em>ISession</em> for NHibernate! Pretty neat We&#8217;re not done yet though. Because the Entity Framework and NHibernate are so different from each other, I decided to implement specific interface for each of those as well. I can imagine different methods might be useful when working with one or the other.</p>
<pre class="brush:csharp">/// &lt;summary&gt;
/// Implement Unit of Work specifically for Entity Framework.
/// Details can be implemented later.
/// &lt;/summary&gt;
public interface IEFUnitOfWork : IUnitOfWork&lt;ObjectContext&gt;
{
}

/// &lt;summary&gt;
/// Implement Unit of Work specifically for NHibernate.
/// Details can be implemented later.
/// &lt;/summary&gt;
public interface INHUnitOfWork: IUnitOfWork&lt;ISession&gt;
{
}</pre>
<p>That&#8217;s it! I have now defined the interfaces that will help me with building a common repository interface and a common way of using concrete repositories. Let&#8217;s go and have a look at the repositories. Here&#8217;s a simple interface for the repositories, it only has three methods for now, but of course you can expand on that to your own liking.</p>
<pre class="brush:csharp">public interface IRepository&lt;T&gt;
{
    T GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch);

    IEnumerable&lt;T&gt; GetMany(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch);

    IEnumerable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch);
}</pre>
<p>I can now use this interface to implement different base repositories for<em> Entity Framework </em>as well as <em>NHibernate</em>.</p>
<p>I will start by showing the implementation for the Entity Framework. If you pay close attention to it, you will see that the <em>AddIncludesToObjectSet()</em> method uses a generic <em>Include&lt;T&gt; </em>method. This is an extension method on top of the <em>ObjectQuery </em>object. I&#8217;ll probably explain this in a follow-up post!</p>
<pre class="brush:csharp">public abstract class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class
{
    private IEFUnitOfWork unitOfWork;
    private ObjectContext objectContext;
    private ObjectQuery&lt;T&gt; objectSet;

    /// &lt;summary&gt;
    /// Constructs an EntityFramework repository.
    /// &lt;/summary&gt;
    /// &lt;param name="unitOfWork"&gt;Unit of Work for repository to work with.&lt;/param&gt;
    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = (IEFUnitOfWork)unitOfWork;
        this.objectContext = this.unitOfWork.Context;
    }

    public virtual T GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet&lt;T&gt;();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .Where(where)
            .FirstOrDefault();
    }

    public virtual IEnumerable&lt;T&gt; GetMany(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet&lt;T&gt;();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .Where(where)
            .AsEnumerable();
    }

    public virtual IEnumerable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        this.objectSet = this.objectContext.CreateObjectSet&lt;T&gt;();
        AddIncludesToObjectSet(eagerFetch);

        return this.objectSet
            .AsEnumerable();
    }

    private void AddIncludesToObjectSet(Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        if (eagerFetch != null)
        {
            foreach (Expression&lt;Func&lt;T, object&gt;&gt; fetch in eagerFetch)
            {
                this.objectSet.Include&lt;T&gt;(fetch);
            }
        }
    }
}</pre>
<p>For the NHibernate repository I came up with the following code below this paragraph. Keep in mind that I&#8217;ve used the alpha version of NHibernate 3.0 and therefor I&#8217;m able to use the NHibernate.Linq namespace easily and call the <em>Query&lt;T&gt;() </em>method on the <em>ISession </em>object!</p>
<pre class="brush:csharp">public abstract class Repository&lt;T&gt; : IRepository&lt;T&gt; where T : class
{
    private INHUnitOfWork unitOfWork;
    private ISession session;

    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = (INHUnitOfWork)unitOfWork;
        this.session = this.unitOfWork.Context.SessionFactory.GetCurrentSession();
    }

    public virtual T GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        IQueryable&lt;T&gt; query = this.session
            .Query&lt;T&gt;()
            .Where(where);

        query = AddFetchMode(query, eagerFetch);

        return query.FirstOrDefault();
    }

    public virtual IEnumerable&lt;T&gt; GetMany(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        IQueryable&lt;T&gt; query = this.session
            .Query&lt;T&gt;()
            .Where(where);

        query = AddFetchMode(query, eagerFetch);

        return query.AsEnumerable();
    }

    public virtual IEnumerable&lt;T&gt; GetAll(Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        IQueryable&lt;T&gt; query = this.session.Query&lt;T&gt;();
        query = AddFetchMode(query, eagerFetch); 

        return query.AsEnumerable();
    }

    private IQueryable&lt;T&gt; AddFetchMode(IQueryable&lt;T&gt; queryable,
        Expression&lt;Func&lt;T, object&gt;&gt;[] eagerFetch)
    {
        if (eagerFetch != null)
        {
            foreach (Expression&lt;Func&lt;T, object&gt;&gt; fetch in eagerFetch)
            {
                queryable = queryable.Fetch(fetch);
            }
        }

        return queryable;
    }
}</pre>
<p>What have I achieved after all this trouble? That I can write our repositories once and never change them, regardless if I&#8217;m working with <em>NHibernate </em>or <em>Entity Framework</em>! Also, this is the part where my useless interface without methods comes into play! I know I have an <em>IUnitOfWork </em>object and I can simply pass it along to the constructor of this repository, regardless of the fact if it is an <em>INHUnitOfWork </em>or <em>IEFUnitOfWork</em>. Perhaps this part can still use a bit of work with type safety, so that there are no accidents with passing along a <em>IEFUnitOfWork </em>to a repository that is expecting a <em>INHUnitOfWork</em>!</p>
<pre class="brush:csharp">public class ConcreteRepository : Repository&lt;TEntity&gt;, IConcreteRepository
{
    public ConcreteRepository(IUnitOfWork unitOfWork)
        : base(unitOfWork)
    {
    }
}</pre>
<p>The only thing I would need to do when I switch between <em>NHibernate </em>or <em>Entity Framework</em> now is to change the using statement and the project references to point to the proper assembly containing the specific classes and interfaces!</p>
<pre class="brush:csharp">using Storminajar.Framework.Data.NHibernate;</pre>
<p>or</p>
<pre class="brush:csharp">using Storminajar.Framework.Data.EntityFramework;</pre>
<p>Of course I would still need to make my application aware of which Unit of Work to use and I would have to implement that logic somewhere, but at least I won&#8217;t have to change my code of my repositories!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/08/30/letting-your-unitofwork-repositories-support-multiple-frameworks/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

