<?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; Design Patterns</title>
	<atom:link href="http://www.storminajar.net/tag/design-patterns/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>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>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>
		<item>
		<title>Generic factory and repositories: Part 2 revisited</title>
		<link>http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/</link>
		<comments>http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/#comments</comments>
		<pubDate>Tue, 18 May 2010 14:13:11 +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[Factory]]></category>
		<category><![CDATA[Repository]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=528</guid>
		<description><![CDATA[This post is part of a series: - Generic factory and repositories: Part 2 revisited - Generic factory and repositories: Part 2 - Generic factory and repositories: Part 1 - WCSF, Repositories and Unit of Work? In Part 2 I discussed my implementation for a SimpleRepositoryFactory. I said that I wasn&#8217;t quite happy with the [...]]]></description>
			<content:encoded><![CDATA[<p>This post is part of a series:<br />
- Generic factory and repositories: Part 2 revisited<br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/">Generic factory and repositories: Part 2</a><br />
- <a href="http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/" target="_blank">Generic factory and repositories: Part 1</a><br />
- <a href="http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/" target="_blank">WCSF, Repositories and Unit of Work?</a></p>
<p>In Part 2 I discussed my implementation for a <em>SimpleRepositoryFactory</em>. I said that I wasn&#8217;t quite happy with the implementation of the factory class, as I would have to adjust my <em>Create() </em>method every time I would add a new repository to the project. At first I was looking for a solution that would let me pass a <em>typeof()</em> into the generic parameter of the <em>InternalRepositoryFactory</em>. For example, I wanted to do something like:</p>
<pre class="brush:csharp">InternalRepositoryFactory&lt;typeof(I), typeof(C)&gt;.Create();</pre>
<p>Of course this doesn&#8217;t work. Generics need to be resolved at compile time and therefore it&#8217;s impossible to create the code I wanted. Or is it?</p>
<p><span id="more-528"></span>There is one way of dynamically inserting types into a generic class and/ or method during runtime: <strong>reflection</strong>! I might be a bit of a nerd, but I love working with reflection. It can do everything! This doesn&#8217;t mean I use it inappropriately, I just happen to like the challenge of diving into completely unreadable code and making stuff work! <img src='http://www.storminajar.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>I managed to adjust my <em>SimpleRepositoryFactory</em> in such a way that I would never need to touch the <em>Create()</em> method again. Even if I add new repositories to the project at a later stage!</p>
<pre class="brush:csharp">public static class SimpleRepositoryFactory
{
    private static Dictionary&lt;Type, Type&gt; repositoryTypes =
        new Dictionary&lt;Type,Type&gt;()

    /// &lt;summary&gt;
    /// Creates repository object based on its interface
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
    /// &lt;param name="args"&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static T Create&lt;T&gt;(params object[] args)
    {
        if (repositoryTypes.ContainsKey(typeof(T)))
        {
            // Create InternalRepositoryFactory&lt;I, C&gt;.
            Type internalFactory =
                typeof(InternalRepositoryFactory&lt;,&gt;);
            internalFactory = internalFactory.MakeGenericType(
                typeof(T), repositoryTypes[typeof(T)]);

            // Get the Create() method from the
            // InternalRepositoryFactory.
            MethodInfo method = internalFactory.GetMethod(
                "Create", BindingFlags.Static |
                BindingFlags.NonPublic);

            // Invoke the Create() method and return the result.
            // For some reason I need to wrap 'args' into a new
            // object[]?
            return (T)method.Invoke(
                internalFactory, new object[] {args});
        }
        else
        {
            throw new Exception("Type: " + typeof(T)
                + " does not exist in dictionary. Register"
                + " the type mappings first by using the"
                + " RegisterTypeMapping method.");
        }
    }

    /// &lt;summary&gt;
    /// Registers the repository types, marking them as
    /// available to use with the RepositoryFactory.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="I"&gt;Interface type of object.&lt;/typeparam&gt;
    /// &lt;typeparam name="C"&gt;Concrete type of object.&lt;/typeparam&gt;
    public static void RegisterTypeMapping&lt;I, C&gt;()
    {
        // Only add the type mapping if it doesn't exist.
        if (!typeMapping.ContainsKey(typeof(I)))
        {               
            typeMapping.Add(typeof(I), typeof(C));
        }
    }
}</pre>
<p>There are multiple downsides to this code.</p>
<p>Even though I don&#8217;t have to touch the <em>Create() </em>method any more, I have to maintain the internal dictionary with definitions. I have moved the problem to a different area in my code. However, the positive side of this is that I can&#8217;t break the implementation by accident. If I need to be able to instantiate a new repository, I will add a new definition to the dictionary, using the <em>RegisterTypeMapping()</em> method.</p>
<p>Another downside is that I&#8217;ve made the code a lot more complex! This does not improve readability or maintainability at all! Imagine a colleague, unschooled in the ways of reflection, needs to make changes to this code while I am on holidays&#8230; the poor bastard would have a very hard time trying to figure it all out!</p>
<p>I can imagine the performance takes a hit as well. I have no clue how much, as I haven&#8217;t bothered to measure. However, I think we can all agree that using reflection to resolve types and invoke methods is a bit more costly than simply invoking a method with generics.</p>
<p>I have no idea whether I should use this code or not. I&#8217;ve wrote it, I&#8217;ve seen it works and I enjoyed the challenge of figuring it out, but all the potential downsides make me scratch my head whether or not I should revert the code back to the way it was. I did write this post in case you, as reader, might really need to do something similar. Therefore I will let you make up your own mind and I won&#8217;t tell you what&#8217;s right or wrong. Just remember to sit down and think it over again when you suspect you need to resolve generics dynamically at runtime!</p>
<p>Lastly, I&#8217;d like to point out that I&#8217;ve moved far away from my original intent of developing a factory to create repositories, instead it has become a very generic class that can instantiate any sort of object as long as it implements an interface that can be returned. I&#8217;m not even sure if it can actually be classified as a factory pattern any more. <em>SimpleRepositoryFactory</em> seems a very inadequate name as it does not describe the actual implementation!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Generic factory with repositories: Part 2</title>
		<link>http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/</link>
		<comments>http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/#comments</comments>
		<pubDate>Tue, 18 May 2010 08:55: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[Factory]]></category>
		<category><![CDATA[Repository]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=511</guid>
		<description><![CDATA[This post is part of a series: - Generic factory and repositories: Part 2 revisited - Generic factory and repositories: Part 2 - Generic factory and repositories: Part 1 - WCSF, Repositories and Unit of Work? Yesterday I posted my musings on using the factory pattern to instantiate my repositories without needing to have a [...]]]></description>
			<content:encoded><![CDATA[<p>This post is part of a series:<br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/" target="_blank">Generic factory and repositories: Part 2 revisited</a><br />
- Generic factory and repositories: Part 2<br />
- <a href="http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/" target="_blank">Generic factory and repositories: Part 1</a><br />
- <a href="http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/" target="_blank">WCSF, Repositories and Unit of Work?</a></p>
<p>Yesterday I posted my musings on using the factory pattern to instantiate my repositories without needing to have a reference to the actual repository class, but only the interface. This morning I made some progress and I have actually managed to create some working code. Some of the code, especially the <em>SimpleRepositoryFactory</em>, can do with a little refinement. However, the basic principle seems to be working and that is all that matters at the moment.</p>
<p><span id="more-511"></span><strong>The Repositories</strong></p>
<p>Let&#8217;s start with the beginning and have a look at how I defined my repository classes and interfaces.</p>
<pre class="brush:csharp">public interface IRepository&lt;T&gt; where T : class
{
    IQueryable&lt;T&gt; AsQueryable();
    IEnumerable&lt;T&gt; GetAll(string[] includes = null);
    IEnumerable&lt;T&gt; GetMany(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        string[] includes = null);
    T GetSingle(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        string[] includes = null);
    T GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; where,
        string[] includes = null);
    void Delete(T entity);
    void Add(T entity);
}</pre>
<pre class="brush:csharp">public abstract class Repository&lt;T&gt; : IRepository&lt;T&gt;
    where T : class
{
    private IUnitOfWork unitOfWork;

    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    #region IRepository members
    // For the sake of simplicity, I'll leave the implementation
    // of the IRepository interface away. I might put up a source
    // code zip package later!
    #endregion
}</pre>
<p>Now that I have the crude basics for a repository, it&#8217;s time to put them to work.</p>
<p>The following code demonstrates how to declare a repository that uses the <em>IRepository</em> interface and the abstract <em>Repository</em> base class. Because the <em>IUserRepository</em> interface implements the <em>IRepository</em> interface, I will be able to call all methods declared in <em>IRepository</em> by talking to my <em>IUserRepository</em>. This is pretty neat, since I won&#8217;t ever need to know anything about the concrete implementations when I start implementing the code in my (web) application.</p>
<pre class="brush:csharp">public interface IUserRepository : IRepository&lt;User&gt;
{
}</pre>
<pre class="brush:csharp">public class UserRepository : Repository&lt;User&gt;, IUserRepository
{
    public UserService(IUnitOfWork unitOfWork)
        : base(unitOfWork)
    {
    }
}</pre>
<p><strong>The generic factory</strong></p>
<p>Now that I&#8217;ve shown you the basics of my repository, I will show you the implementation of my <em>SimpleRepositoryFactory</em>. Mind you, it&#8217;s nothing special and it&#8217;s exactly what the name suggests; simple.</p>
<pre class="brush:csharp">public static class SimpleRepositoryFactory
{
    public static T Create&lt;T&gt;(params object[] args)
    {
        if (typeof(T) == typeof(IUserService))
        {
            // Excuse me for the code mark-up here!
            return (T)InternalRepositoryFactory&lt;IUserService,
                UserService&gt;.Create(args);
        }
        else
        {
            return default(T);
        }
    }
}</pre>
<p>The downside of using this approach is that I will have to edit the <em>SimpleRepositoryFactory</em> with every new repository class I might add. A little inconvenient, but for now it suits me fine as I will only need to add it in the <em>Create()</em> method of the factory by using another <em>else-if </em>statement. You might notice that this class calls <em>InternalRepositoryFactory</em> to actually instantiate the object.</p>
<p>The <em>InternalRepositoryFactory</em> is actually a very generic object factory. It will be able to create any object, as long as the object implements the specified interface.</p>
<pre class="brush:csharp">internal static class InternalRepositoryFactory&lt;I, C&gt; where C : I
{
    internal static I Create(params object[] args)
    {
        return (I)Activator.CreateInstance(typeof(C), args);
    }
}</pre>
<p><strong>Using the factory!</strong></p>
<p>Now that I&#8217;ve got all the pieces of the puzzle, it&#8217;s time to start putting it all together. Notice how I will still be able to use my repositories and unit of work as I described <a href="http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/" target="_blank">here</a>! Not only that, but I&#8217;m also using interfaces instead of instantiating concrete implementations of my repositories!</p>
<pre class="brush:csharp">using (TransactionScope ts = new TransactionScope())
{
    using (IUnitOfWork uof = new ConcreteUnitOfWork())
    {
        // Get reference to UserRepository.
        IUserRepository ur =
            SimpleRepositoryFactory.Create&lt;IUserRepository&gt;(uof);

        // Get all users.
        List&lt;User&gt; users = ur.GetAll().ToList();

        // You can create more repositories here and
        // do additional work using this unit of work
        // and transaction scope!

        // We're done!
        uof.Commit();
        ts.Complete();
    }
}</pre>
<p><strong>Conclusion</strong></p>
<p>I&#8217;m not really sure if this approach is correct, but for now I have solved the problem that I posted about yesterday in <a href="http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/" target="_blank">Part 1</a>. This solution will allow me to create different modules and have interaction between them by only using their interfaces without needing to instantiate concrete implementations that would make my code too tightly coupled. I&#8217;m not quite happy with the implementation of <em>SimpleRepositoryFactory</em> and I will continue to look for a more elegant solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Generic factory with repositories: Part 1</title>
		<link>http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/</link>
		<comments>http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/#comments</comments>
		<pubDate>Mon, 17 May 2010 18:06:36 +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[Factory]]></category>
		<category><![CDATA[Repository]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=504</guid>
		<description><![CDATA[This post is part of a series: - Generic factory and repositories: Part 2 revisited - Generic factory and repositories: Part 2 - Generic factory and repositories: Part 1 - WCSF, Repositories and Unit of Work? My previous post was about using WCSF in combination with repositories and a unit of work. I didn’t have [...]]]></description>
			<content:encoded><![CDATA[<p>This post is part of a series:<br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/" target="_blank">Generic factory and repositories: Part 2 revisited</a><br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/">Generic factory and repositories: Part 2</a><br />
- Generic factory and repositories: Part 1<br />
- <a href="http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/" target="_blank">WCSF, Repositories and Unit of Work?</a></p>
<p>My previous post was about using WCSF in combination with repositories and a unit of work. I didn’t have any clear answers then and I don’t have any clear answers now. It doesn’t matter any more though, since I decided to drop WCSF entirely and pursue my own implementation of a modular web application, based on MVP, where I can still use my repositories as I would like.</p>
<p>The reasons why I’m doing this don’t matter. It has some very solid grounds, but I won’t discuss them as it’s not in the scope of this post.</p>
<p>Let’s take a look at the situation I’m faced with for a new proof of concept project:</p>
<p><span id="more-504"></span>I need to be able to make a simple modular web application. Users would need to be able to enter meeting-reports as well as enter activities. However, some issues in the meeting will have led to activities needing to be completed. So it should also be possible to create activities when entering a meeting-report.</p>
<p>In this case I will have two modules in my system: <em>MeetingReports </em>and <em>Activities</em>. The MeetingReports module will need to use the <em>ActivitiesRepository </em>within the Activities module to be able to create activities.</p>
<p>I won’t go into details, but WCSF had this nicely covered by working with dependency injection and interface libraries. That’s a practice from WCSF that I would like to adapt. However, I can’t simply make a reference from MeetingReports to the activties interfaces. I will have to instantiate a concrete class at some point!</p>
<p>What if I would be able to make a generic factory that instantiates repositories for me and returns their interface? I would be able to use the repositories without needing to know anything about their implementations.</p>
<p>I don’t have any concrete code yet (what a surprise!), but I would imagine something similar to this might be very possible:</p>
<pre class="brush:csharp">using (IUnitOfWork uof = new UnitOfWork)
{
    IMeetingReportRepository irr =
        RepositoryFactory.Create&lt;IMeetingReportRepository&gt;(uof);
    irr.Insert(meetingReport);

    IActionRepository iar =
        RepositoryFactory.Create&lt;IActionRepository&gt;(uof);

    // Save all activities.
    foreach (Activity a in meetingReport.Activities)
    {
        iar.Insert(a);
    }

    uof.Commit();
}</pre>
<p>The factory class would know how to instantiate <em>ActionRepository </em>based on the fact that its create method has been called with an <em>IActionRepository </em>generic! This way the factory will do the concrete instantiation while the activities module will only see, and use, the interface!</p>
<p>Hopefully I will be able to show some working C#-code soon, so stay tuned (yes, again)…</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>WCSF, Repositories and Unit of Work?</title>
		<link>http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/</link>
		<comments>http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/#comments</comments>
		<pubDate>Tue, 11 May 2010 13:44:04 +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[Entity Framework]]></category>
		<category><![CDATA[WCSF]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=496</guid>
		<description><![CDATA[This post is part of a series: - Generic factory and repositories: Part 2 revisited - Generic factory and repositories: Part 2 - Generic factory and repositories: Part 1 - WCSF, Repositories and Unit of Work? In my research for designing and implementing modular web applications, I&#8217;ve come across the Web Client Software Factory. I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>This post is part of a series:<br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-and-repositories-part-2-revisited/" target="_blank">Generic factory and repositories: Part 2 revisited</a><br />
- <a href="http://www.storminajar.net/2010/05/18/generic-factory-with-repositories-part-2/">Generic factory and repositories: Part 2</a><br />
- <a href="http://www.storminajar.net/2010/05/17/generic-factory-with-repositories/" target="_blank">Generic factory and repositories: Part 1</a><br />
- WCSF, Repositories and Unit of Work?</p>
<p>In my research for designing and implementing modular web applications, I&#8217;ve come across the <a href="http://webclientguidance.codeplex.com/" target="_blank">Web Client Software Factory</a>. I&#8217;ve already briefly touched this subject in a <a href="http://www.storminajar.net/2010/04/28/creating-modular-web-applications/" target="_blank">previous post</a>. It heavily uses the <a href="http://msdn.microsoft.com/en-us/library/ff648195.aspx" target="_blank">Composite Web Application Block</a> to implement a Model-View-Presenter approach for a web application. It allows developers to <em>compose</em> applications from different pieces  of software (<em>modules</em>). One of the advantages of this approach is that these modules can be developed independently from each other by different teams of developers. Another advantage is that the entire web application consists of separate blocks of software that are <em>loosely coupled</em>. I&#8217;m sure you&#8217;ve heard that term used by someone before!</p>
<p>As I was evaluating WCSF I stumbled on an interesting question. A question which I have no answer to yet.</p>
<p>In the past I&#8217;ve successfully used Microsoft&#8217;s <a href="http://msdn.microsoft.com/en-us/library/aa697427%28VS.80%29.aspx" target="_blank">Entity Framework</a>. It&#8217;s relatively straight forward to implement a <em>Repository Pattern</em> in combination with a <em>Unit of Work</em>. If you have no idea what I&#8217;m talking about, <a href="http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/10/08/the-repository-pattern.aspx" target="_blank">here</a> is a nice example. Admittedly, it&#8217;s an implementation for <a href="http://community.jboss.org/wiki/NHibernateforNET" target="_blank">NHibernate</a>, but it can just as easily be implemented for EF. The beauty of this approach was that I could use a single <em>ObjectContext </em>and pass it on to multiple repositories. This allowed me to use different repository classes in the same <em>TransactionScope</em>.</p>
<p>Here&#8217;s a quick example to show what I mean:</p>
<pre class="brush:csharp">using (TransactionScope ts = new TransactionScope())
{
    // Create unit of work.
    using (IUnitOfWork uof = new ConcreteUnitOfWork())
    {
        // Create repositories and pass unit of work.
        OrderRepository or = new OrderRepository(uof);
        CustomerRepository cr = new CustomerRepository(uof);

        // place order in the system.
        or.Insert(customer.Order);

        // update order history for the customer.
        cr.UpdateHistory(customer);

        // So far, so good! Save all the changes.
        uof.Commit();
        ts.Complete();
    }
}</pre>
<p>This is a simple piece of code that shows a single transaction over multiple repositories. In this scenario I had complete control over creating an ObjectContext and releasing its resources (<em>IUnitOfWork</em> implements <em>IDisposable</em> which will clean up any resources). In this way I had full control over creating a fresh ObjectContext for each new business transaction and automatically disposing it when the code finishes executing the <em>using-</em>statement.</p>
<p>I wanted to have the same functionality with implementing WCSF. I&#8217;ve had a good long look at the sample <em>OrderManagementRI</em> implementation that comes with the WCSF sources. It&#8217;s an excellent example of how they implement repositories and use them as a <em>service</em> within a module. I&#8217;ve been able to recreate a similar scenario in my proof of concept application, but I found I no longer have any control on my <em>IUnitOfWork</em> since it is created and passed on to the repositories by using <em>Dependency Injection</em>.</p>
<p>I&#8217;ve been searching on the web for a solution, but so far I&#8217;ve not found it yet. I&#8217;d like to have the same functionality with my <em>IUnitOfWork</em>. I want to be able to create a new one to pass along to multiple repositories in a transaction, while still having the benefits of the modular service approach of WCSF. I have a feeling that I should be able to create something much more to my liking if only I understood more of both WCSF and <em>Dependency Injection </em>principles.</p>
<p>To be continued (again)&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/05/11/wcsf-repositories-and-unit-of-work/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating modular web applications</title>
		<link>http://www.storminajar.net/2010/04/28/creating-modular-web-applications/</link>
		<comments>http://www.storminajar.net/2010/04/28/creating-modular-web-applications/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 10:17:15 +0000</pubDate>
		<dc:creator>Rob Jones</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.storminajar.net/?p=448</guid>
		<description><![CDATA[Before you read on, if you stumbled on this link through a search engine I will not waste your time and say I won&#8217;t be telling you how to do it. Instead, I&#8217;m going to share my experience of researching this topic. It all sounds so beautiful. The idea of creating a web application that [...]]]></description>
			<content:encoded><![CDATA[<p>Before you read on, if you stumbled on this link through a search engine I will not waste your time and say I won&#8217;t be telling you how to do it. Instead, I&#8217;m going to share my experience of researching this topic.</p>
<p>It all sounds so beautiful. The idea of creating a web application that is built by separate blocks of functionality that can be developed independently of each other, but are still smart enough to work together if necessary. I started out thinking that I wouldn&#8217;t be the first person to have this brilliant idea and that there would be plenty helpful topics to help me get my journey underway. I had absolutely no idea what I would get myself into! Believe me when I tell you that implementing this idea is easier said then done!</p>
<p>I&#8217;ve always considered myself an able software developer who likes to dabble with getting projects started and setting up their architectures. Who have I been kidding?! Shortly after starting my research it was evident that there&#8217;s no out-of-the-box solution readily available. There are in fact a lot of ways to achieve this goal.</p>
<p>In the past week(s) I have found that my knowledge did not carry me as far as I had expected it would. I&#8217;ve read various books on <em>Design Patterns</em> and supposed that I understood most of the concepts I had read about. After having read many articles, I&#8217;ve been beaten to death with a lot of complicated words. <em>Separation of Concerns,</em> <em>Model View Controller, Model View Presenter </em>(and all their various little brothers and sisters),<em> Inversion of Control, Dependency Injection</em> and I could continue adding terms this list! Eventually I found myself reading up on <em>Workflow Foundation</em> and <em>Service Oriented Architectures</em> as well.</p>
<p>It made me scratch my head. I&#8217;ve read about most and heard about others, but found that my knowledge doesn&#8217;t extend past that. I&#8217;m hazy on the actual implementation of all these patterns and there&#8217;s such an abundance of literature to read that I feel I&#8217;m getting deviated from my original goal. However, getting to that goal will require me to dust off some of my knowledge and start polishing it to a shine again&#8230; It&#8217;s a nasty little circle that I will have to break out of. In any case it&#8217;s proving the point of what I was trying to convey to my old employer, it&#8217;s important to know about<em> </em>design patterns and their implementations!</p>
<p>At the moment I&#8217;m edging towards the possibility of a proof of concept implementation using the <em>Model View Presenter</em> design pattern in combination with <em>ASP.NET WebForms</em>. As far as I can tell right now this is going to be the most flexible way and reap the best of both worlds: seperation of concerns with an MVP approach (probably aided by <a href="http://msdn.microsoft.com/en-us/library/cc304856.aspx" target="_blank">Composite Web Application Block</a>), combined with the strength and productivity WebForms can bring in terms of controls, such as <a href="http://www.telerik.com" target="_blank">Telerik</a>.</p>
<p>Perhaps I will follow up on this topic later when I have a clearer vision on which approach to take and why.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.storminajar.net/2010/04/28/creating-modular-web-applications/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

