<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Aspiring Craftsman</title>
	
	<link>http://www.aspiringcraftsman.com</link>
	<description>pursuing well-crafted software</description>
	<lastBuildDate>Tue, 02 Mar 2010 22:35:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/AspiringCraftsman" /><feedburner:info uri="aspiringcraftsman" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Resharper Naming Style for Machine.Specifications</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/IBBmroY_lVc/</link>
		<comments>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 01:59:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Machine.Specifications]]></category>
		<category><![CDATA[Resharper]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/?p=222</guid>
		<description><![CDATA[If you&#8217;re doing BDD-style specifications and using underscores within your variable names, the default Resharper settings will warn you about violating the naming style rules as shown below:

Fortunately, Machine.Specifications (MSpec) extends Resharper to allow for the creation of custom rules which affect only your MSpec types.  To create a custom rule for MSpec, follow [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re doing BDD-style specifications and using underscores within your variable names, the default Resharper settings will warn you about violating the naming style rules as shown below:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperUnconfigured.png"><img class="size-full wp-image-223" title="ResharperUnconfigured" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperUnconfigured.png" alt="" width="661" height="442" /></a></p>
<p>Fortunately, Machine.Specifications (MSpec) extends Resharper to allow for the creation of custom rules which affect only your MSpec types.  To create a custom rule for MSpec, follow these steps:</p>
<p><strong>Step 1</strong>: Open the Resharper Options Dialog.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptions.png"><img class="alignnone size-full wp-image-255" title="ResharperOptions" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptions.png" alt="" width="229" height="453" /></a></p>
<p><strong>Step 2</strong>: Navigate to Languages | Naming Style and under &#8220;User defined naming rules&#8221; click &#8220;Add&#8221;.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyle_add.png"><img class="size-full wp-image-224" title="ResharperOptionsLanguagesNamingStyle_add" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyle_add.png" alt="" width="622" height="599" /></a></p>
<p><strong>Step 3</strong>: This displays the &#8220;Edit Extended Naming Rule dialog.  In the &#8220;Rule Definition:&#8221; text box, give your new rule a name such as &#8220;Machine.Specifications Rules&#8221;.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescription.png"><img class="alignnone size-full wp-image-261" title="ResharperOptionsLanguagesNamingStyleRuleDescription" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescription.png" alt="" width="492" height="446" /></a></p>
<p><strong>Step 4</strong>: Within the Affected entities list, un-check Class and scroll to the bottom to locate the entries starting with Machine.Specifications.  Select all of these entries.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescriptionModified.png"><img class="alignnone size-full wp-image-260" title="ResharperOptionsLanguagesNamingStyleRuleDescriptionModified" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleDescriptionModified.png" alt="" width="492" height="443" /></a></p>
<p><strong>Step 5</strong>: Select all options under Access rights: and leave options under Static/non-static: selected.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleAccessRights.png"><img class="alignnone size-full wp-image-263" title="ResharperOptionsLanguagesNamingStyleAccessRights" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleAccessRights.png" alt="" width="483" height="190" /></a></p>
<p><strong>Step 6</strong>: Add a new naming style to associate this rule to by clicking the Add icon and selecting the desired naming style (e.g. all_lower).</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleStyle.png"><img class="alignnone size-full wp-image-264" title="ResharperOptionsLanguagesNamingStyleRuleStyle" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperOptionsLanguagesNamingStyleRuleStyle.png" alt="" width="224" height="622" /></a></p>
<p>The following diagram shows the dialog after these steps:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperEditExtendedNamingRuleDialog.png"><img class="size-full wp-image-249" title="ResharperEditExtendedNamingRuleDialog" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperEditExtendedNamingRuleDialog.png" alt="" width="650" height="598" /></a></p>
<p style="padding: 10px;">After selecting OK, Resharper now ignores the naming warnings for the MSpec types:</p>
<div><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperConfigured.png"><img class="size-full wp-image-266" title="ResharperConfigured" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2010/02/ResharperConfigured.png" alt="" width="648" height="440" /></a></div>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/IBBmroY_lVc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/</feedburner:origLink></item>
		<item>
		<title>Embracing Dependency Injection</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/eh5vu0wR3AE/</link>
		<comments>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 14:59:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependency Injection]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/</guid>
		<description><![CDATA[Recently, a fairly notable icon within the software development community posted some thoughts on Twitter which I found surprising.  The individual stated:
 &#8220;What&#8217;s the right number of dependencies to inject?  A few.  In a very large system, perhaps a few dozen.&#8221; 
Given that I found this statement to be fairly controversial, I [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, a fairly notable icon within the software development community posted some thoughts on Twitter which I found surprising.  The individual stated:</p>
<p style="padding-left: 30px;"><em> &#8220;What&#8217;s the right number of dependencies to inject?  A few.  In a very large system, perhaps a few dozen.&#8221; </em></p>
<p>Given that I found this statement to be fairly controversial, I urged the individual to write an article explaining what had brought them to such a conclusion.  Later that day, an article was published on the subject explaining their position.  After reading the article, it became clear that what was being argued against was the degree of coupling to a dependency injection framework, not dependency injection in general.  While minimizing an application&#8217;s degree of coupling to any given framework is a goal to be encouraged, the argument was partially based upon a lack of familiarity with the conventional use of dependency injection containers.</p>
<p>In an effort to demonstrate that use of a dependency injection framework is usually unnecessary,the article presents two versions of an example billing application with and without relying upon a framework.  The following is a C# version approximating the examples presented within the article:</p>
<p><strong>Dependency Injection Framework Version</strong></p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            IContainer container = new Container().AddConfiguration(BillingConfiguration);
            BillingService billingService = container.Resolve&lt;BillingService&gt;();

            // TODO: do something with the billing service ...
        }
    }

    public class BillingConfiguration : ContainerConfiguration
    {
        protected void Configure()
        {
             Register&lt;ICreditCardService&gt;().As&lt;CreditCardService&gt;();
             Register&lt;ITransactionLog&gt;().As&lt;DatabaseTransactionLog&gt;();
        }
    }
</pre>
<p><strong>Manual Dependency Injection Version</strong></p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            BillingService billingService = new BillingService(new CreditCardProcessor(), new TransactionLog());

            // TODO: do something with the billing service ...
        }
    }
</pre>
<p>Comparing the two examples, the second is obviously the more straight forward and concise of the two approaches.</p>
<p>Foreseeing the concern that one might want to use the billing service in a lower layer of the application, the article proceeds to set forth an example which configures a globally accessible static instance of the service within the main method:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            BillingService billingService = new BillingService(new CreditCardProcessor(), new TransactionLog());
            BillingService.Instance = billingService;

            // Now the BillingService.Instance can be accessed anywhere within the application
        }
    }
</pre>
<p>To further address the need to create separate instances of the billing service, the article next presents an example which configures a globally accessible Factory instance which can be accessed from other parts of the application.  Perhaps in an attempt to show some recognition of the benefits of using a framework, the Factory is designed to encapsulate the registration and use of a container for retrieving instances of the billing service:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            IContainer container = new Container().AddConfiguration(BillingConfiguration);
            BillingService.Factory = new BillingServiceFactory(container);

            // Now we can make new instances of the billing service anywhere within the application
            BillingService billingService = BillingService.Factory.Create();
        }
    }

    public class BillingServiceFactory : ContainerConfiguration
    {
        IContainer _container;

        public BillingServiceFactory(IContainer container)
        {
            _container = container;
        }

        protected void Configure()
        {
             Register&lt;ICreditCardService&gt;().As&lt;CreditCardService&gt;();
             Register&lt;ITransactionLog&gt;().As&lt;DatabaseTransactionLog&gt;();
        }

        public BillingService Create()
        {
            return _container.Resolve&lt;BillingService&gt;() ;
        }
    }
</pre>
<p>The article concludes by submitting that dependency injection frameworks should only be used for areas of an application that are known extension points, and that in most cases the best course of action is to manually instantiate any needed objects along with their dependencies.</p>
<p>While these examples may seem perfectly sensible to those unfamiliar with using a dependency injection framework, there are several problems with the techniques presented here.</p>
<p>First, the simplicity of these examples fail to highlight the issues involved in real-world applications.  Applications designed with an adherence to low-coupling and preferring composition over inheritance often result in object grafts many levels deep.  That is to say, the dependencies of one object may have dependencies of their own, which in turn have dependencies of their own, and so forth and so on.  While it is possible to use the manual instantiation techniques described in the first example, the resulting code will soon become both unsightly and unwieldy.  Couple that with the reuse of components across multiple types and duplication starts to arise.  The examples above don&#8217;t highlight these issues since they are only working with a simple object graph.</p>
<p>Second, issues arise in the introduction of global variables to access instances of the billing service or the factory.  For one, the design becomes more opaque.  Classes which reference global resources don&#8217;t express their external dependencies through their interface thereby requiring you to look at the code to discover what dependencies are required.  Two, this introduces a responsibility to the billing service which isn&#8217;t an inherent concern.  The responsibility for the creation and lifetime management of the service is a separate concern from the service&#8217;s core responsibilities and one which can change for different reasons.</p>
<p>Third, the encapsulation of the container registration and resolution of the billing service within the factory actually serves to more tightly couple the application to the dependency injection framework.  What&#8217;s been missed in the examples thus far is the fact that the billing service is itself a dependency of other types and they in turn may themselves be dependencies.  By ensuring that all types within the system are using dependency injection, the entire dependency chain can be resolved by one call to the container.  This eliminates the need to produce specialized factories for each type.</p>
<p>Consider the following example:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public static void Main()
        {
            new Bootstrapper().Run();
        }
    }

    public class Bootstrapper
    {
        public void Run()
        {
            ConfigureContainer();
            Container.Resolve&lt;IShell&gt;().Show();
        }

        void ConfigureContainer()
        {
            // Configure the container
        }
    }

    public interface IBillingService
    {
        // define billing methods
    }

    public class BillingService : IBillingService
    {
        public BillingService(ICreditCardProcessor creditCardProcessor, ITransactionLog transactionLog) { ... }

        // implement IBillingService methods here
    }

    public interface IShell
    {
         void Show();
    }

    public class Shell : IShell
    {
        public Shell(IBillingService billingService) { ... }

        public void Show() { ... }
    }
</pre>
<p>In this example the container is only referenced from within the Bootstrapper and the container is only used to resolve an instance of the type IShell.  Given that all types have been registered, the container traverses the dependency chain, building up the object graph from the bottom up.  This allows the entire application to remain decoupled from the dependency injection framework as well as avoiding the need to create and further maintain type specific factories.  As the application grows in complexity, there may be the need to introduce other entry points or strategies for handling lazy-loading, but coupling to the container would remain minimal.</p>
<p>If you find yourself needing to invert your dependencies on an inversion of control framework then you are doing it wrong.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/eh5vu0wR3AE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2010/01/embracing-dependency-injection/</feedburner:origLink></item>
		<item>
		<title>The Arrow Anti-pattern</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/SH_kzuPdKaY/</link>
		<comments>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 09:46:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Arrow Anti-pattern]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/</guid>
		<description><![CDATA[The Arrow Ani-pattern is a name given to the resulting structure produced by using excessive nested conditional operators.  The following pseudo-code demonstrates why the name is apt:

if( ... )
{
    if( ... )
    {
        if( ... )
      [...]]]></description>
			<content:encoded><![CDATA[<p>The Arrow Ani-pattern is a name given to the resulting structure produced by using excessive nested conditional operators.  The following pseudo-code demonstrates why the name is apt:</p>
<pre class="brush: csharp;">
if( ... )
{
    if( ... )
    {
        if( ... )
        {
            if( ... )
            {
                if( ... )
                {
                    //--&gt; do something
                }

            }
        }
    }
}
</pre>
<p>The structure above becomes increasingly problematic as each additional nested condition adds to the cognitive load required to parse the represented logic.  According to studies performed by Noam Chomsky and Gerald Weinberg in 1986, few people can easily understand more than three levels of nested conditional statements.  It is therefore recommended that techniques for restructuring the code be sought out when this pattern begins to emerge.</p>
<h2>Guard Clauses</h2>
<p>One approach to refactoring the arrow anti-pattern is to use guard clauses.  Guard clauses are a form of assertion which makes a tangible contribution to the logic of the method.  By restructuring nested conditional statements to successive conditional exit points, the code becomes easier to understand and eases further refactoring efforts such as method extraction or clause reordering.</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    if( ... )
        return;

    // do something
}
</pre>
<h2>Method Extraction</h2>
<p>Another approach especially suited to blocks comprised of nested looping structures is the extraction of segments into separate methods.  For each block forming the body of a loop statement, extract the body into a separate method which can then be examined independently of the containing loop statement:</p>
<p>Before</p>
<pre class="brush: csharp;">
    void SomeProcess()
    {
        while( ... )
        {
            while( ... )
            {
                while( ... )
                {
                    while( ... )
                    {
                    }
                }
            }
        }
    }
</pre>
<p>After</p>
<pre class="brush: csharp;">
    void SomeProcess()
    {
        while( ... )
        {
            MethodA();
        }
    }

    void MethodA()
    {
        while( ... )
        {
            MethodB();
        }
    }

    void MethodB()
    {
        while( ... )
        {
            MethodC();
        }
    }

    void MethodC()
    {
        while( ... )
        {
            MethodD();
        }
    }
</pre>
<h2>Logical And/Or</h2>
<p>In cases where the nested structure is comprised solely of checks against the state of an object, the conditions can be extracted into a collection of Boolean methods and combined to form a more concise and readable guard clause:</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    if(ConditionA() &amp;&amp;
          ConditionB() &amp;&amp;
          ConditionC() &amp;&amp;
          (ConditionD1() || ConditionD2()) &amp;&amp;
          ConditionE())
    {
        // do something
    }
}
</pre>
<h2>Composite Specification Chain</h2>
<p>As a variant to the previous technique, the Specification pattern can be used in the form of a composite specification chain to render a concise and readable guard clause.  Using this technique, specification classes are written to test each case, and the resulting set of specifications are composed into a single composite specification which can evaluate the state of the given object.  Due to the encapsulation of the evaluation logic in the form of separate specification classes, this technique has the added benefit of enabling substitution of the specification implementation via the Strategy pattern for test isolation or other variable composition needs.</p>
<pre class="brush: csharp;">
void SomeProcess()
{
    ISpecification&lt;SomeType&gt; specification = new IsConditionA()
        .And(new IsConditionB())
        .And(new IsConditionC())
        .And(new IsConditionD1().Or(IsConditionD2()))
        .And(new IsConditionE());

    specification.IsSatisfiedBy(this).Then(() =&gt; { /* do something */ });
}
</pre>
<h2>Conclusion</h2>
<p>The techniques presented here are a few approaches to helping achieve more readable and maintainable code by eliminating the arrow anti-pattern.  Through the judicious application of these techniques, developers can in small ways leave their code base cleaner than they found it.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/SH_kzuPdKaY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/10/the-arrow-anti-pattern/</feedburner:origLink></item>
		<item>
		<title>Composite Applications with NHibernate</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/ZlYqveFSJ2U/</link>
		<comments>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 12:12:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Composite Application Development]]></category>
		<category><![CDATA[NHibernate]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/</guid>
		<description><![CDATA[Composite application architecture is an approach to software development which seeks to produce applications which can be constructed from pre-built components, thus allowing a single platform to be more easily customized for end users.
The pre-built components, or modules, comprising a composite application often share data access concerns such as the need to access a central [...]]]></description>
			<content:encoded><![CDATA[<p>Composite application architecture is an approach to software development which seeks to produce applications which can be constructed from pre-built components, thus allowing a single platform to be more easily customized for end users.</p>
<p>The pre-built components, or modules, comprising a composite application often share data access concerns such as the need to access a central database. The use of object-relational mapping frameworks are an increasingly common strategy for facilitating data access needs. This is due to their ability to minimize much of the repetitive, low-level data access coding often required by more traditional approaches, and their ability to abstract much of the idiosyncrasies of specific database vendors, providing greater potential for portability between vendors.</p>
<p>NHibernate, arguably the leading object-relational mapping framework for the .Net platform, facilitates object-relational mapping through a centrally configured component called the SessionFactory. A SessionFactory is configured with the connection parameters for a specific database along with the mapping meta-data required for associating objects to the relational data within the database.</p>
<p>It is generally advised that a single SessionFactory be created per database. This is both due to the overhead required in its creation, and in order to facilitate various caching strategies such as the caching of generated SQL statements, and of entities across sessions (referred to as the second-level cache).</p>
<p>For composite applications, configuration of the SessionFactory can pose a bit of an obstacle given that any centralization of the mapping configuration would tend to couple otherwise independent and optional modules together. Additionally, a centralized configuration of the mappings for each of the modules precludes encapsulation of the configuration needs within each module, and can introduce maintenance complexity for modules developed by separate development teams or organizations. On the other hand, allowing modules to maintain their own SessionFactory for a shared database instance introduces startup overhead and precludes taking advantage of the caching features of the framework.</p>
<p>As demonstrated in the remainder of this article, one approach to solving these challenges is to create a staged application bootstrapping process which both facilitates decentralized mapping registration and centralized SessionFactory initialization.</p>
<p>While potentially applicable in other usage scenarios, the following approach is based upon the use of Fluent NHibernate, the Prism composite application library, and the staged bootstrapping strategy presented within the article: <a href="2009/05/enhancing-the-prism-module-initialization-lifecycle/">Enhancing the Prism Module Initialization Lifecycle</a>.</p>
<p>Our first step in demonstrating this strategy will be to create a module named DataModule which will serve as an infrastructure-only Prism module for configuring NHibernate. Using the ModuleBase implementation of IModule presented in the aforementioned article, the OnPreInitialization() and OnPostInitialization() methods will be overridden.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module
{
    public class DataModule : ModuleBase
    {
        readonly IUnityContainer _container;

        public DataModule(IUnityContainer container)
        {
            _container = container;
        }

        protected override void OnPreInitialization()
        {
        }

        protected override void OnPostInitialization()
        {
        }
    }
}
</pre>
<p>The OnPreInitialization() method will be used to register services to be consumed by other modules while the OnPostInitialization phase will be used to perform the final database configuration.</p>
<p>Next, let’s create a CustomerModule which represents a module using NHibernate for its data access needs. This module need only override the OnInitialization() method to gain access to services registered during the Pre-Initialization bootstrapping phase.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module
{
    public class CustomerModule : ModuleBase
    {
        readonly IUnityContainer _container;

        public DataModule(IUnityContainer container)
        {
            _container = container;
        }

        protected override void OnInitialization()
        {
        }
    }
}
</pre>
<p>Next, we’ll define a mapping service to be used by our CustomerModule for registering which map types and/or assemblies are to be included during the configuration of the SessionFactory.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Services
{
    public interface IMappingRegistryService
    {
        void AddMap() where T : IClassMap;
        void AddMap(Type classMap);
        void AddMapsFromAssemblyOf();
        void AddMapsFromAssembly(Assembly assembly);
    }
}
</pre>
<p>Next, we’ll provide an internal implementation of the mapping service to be contained within t<br />
he DataModule. Two additional properties, Assemblies and Types, are provided to enable the DataModule to access any mapping types and assemblies registered by modules during the Initialization phase.</p>
<pre class="brush: csharp;">
namespace CompositeSpike.Data.Module.Services
{
    class MappingRegistryService : IMappingRegistryService
    {
        readonly IList _assemblies;
        readonly List _types;

        public MappingRegistryService()
        {
            _assemblies = new List();
            _types = new List();
        }

        public IEnumerable Assemblies
        {
            get { return _assemblies; }
        }

        public IEnumerable Types
        {
            get { return _types; }
        }

        public void AddMap() where T : IClassMap
        {
            AddMap(typeof (T));
        }

        public void AddMap(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(&quot;type&quot;);
            }

            if (!_types.Contains(type))
            {
                _types.Add(type);
            }
        }

        public void AddMapsFromAssemblyOf()
        {
            AddMapsFromAssembly(typeof (T).Assembly);
        }

        public void AddMapsFromAssembly(Assembly assembly)
        {
            if (!_assemblies.Contains(assembly))
            {
                _assemblies.Add(assembly);
            }
        }
    }
}
</pre>
<p>With the service defined, let’s return to the DataModule and complete the body of the initialization methods.</p>
<p>To ensure the mapping service is available during the initialization phase of the other modules within the application, the IMappingRegistryService and its internal implementation need to be registered as a singleton with the Unity container during the PreInitialization bootstrapping phase:</p>
<pre class="brush: csharp;">
        protected override void OnPreInitialization()
        {
            _container.RegisterType(new ContainerControlledLifetimeManager());
        }
</pre>
<p>After modules have been given an opportunity to register mappings with our service during the Initialization phase, the service can be retrieved and used to supply the class map types and/or assemblies required for the Fluent NHibernate configuration:</p>
<pre class="brush: csharp;">
        protected override void OnPostInitialization()
        {
            var service = _container.Resolve() as MappingRegistryService;

            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(OracleConfiguration.Oracle9
                              .ConnectionString(
                              c =&gt; c.Is(ConfigurationManager.ConnectionStrings[&quot;example&quot;].ConnectionString))
                              .ShowSql())
                .Mappings(m =&gt;
                    {
                        service.Types.ForEach(t =&gt; m.FluentMappings.Add(t));

                        service.Assemblies.ForEach(a =&gt; m.FluentMappings.AddFromAssembly(a));
                    })
                .BuildSessionFactory();

            _container
                .RegisterInstance(new NHibernateDatabaseContext(sessionFactory),
                                  new ContainerControlledLifetimeManager());
        }
</pre>
<p>Our final step is to complete the initialization method within our CustomerModule to register any desired mappings to be used by the DataModule:</p>
<pre class="brush: csharp;">
        protected override void OnInitialization()
        {
            var dataMappingService = _container.Resolve();
            if (dataMappingService != null) dataMappingService.AddMapsFromAssemblyOf();
        }
</pre>
<p>That concludes our example.</p>
<p>By utilizing a mapping service in conjunction with a multi-phased initialization strategy, a proper level of separation of concerns can be maintained for the modules within a composite application while at the same time utilizing NHibernate’s SessionFactory in the prescribed manner.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/ZlYqveFSJ2U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/06/composite-applications-with-nhibernate/</feedburner:origLink></item>
		<item>
		<title>Unity: The Static Factory Extension</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/c9quajfUXnA/</link>
		<comments>http://www.aspiringcraftsman.com/2009/06/unity-static-factory-extension/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 06:34:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/06/unity-the-static-factory-extension/</guid>
		<description><![CDATA[The Unity Inversion of Control container comes with an extension called the StaticFactoryExtension. The purpose of this extension is to add the ability to register types within the container while deferring the instantiation of the type to a factory method. This enables a number of scenarios where finer-grained control over the construction of an object [...]]]></description>
			<content:encoded><![CDATA[<p>The Unity Inversion of Control container comes with an extension called the StaticFactoryExtension. The purpose of this extension is to add the ability to register types within the container while deferring the instantiation of the type to a factory method. This enables a number of scenarios where finer-grained control over the construction of an object is desired.</p>
<p>As the name suggests, one example use of the extension is with a static factory method. In the following test, an ILoggingService is registered with the container by configuring it to call the LoggingService.GetLoggingService() static method via the IStaticFactoryConfiguration.</p>
<pre class="brush: csharp;">
namespace StaticFactoryExample
{
    public class StaticFactoryExampleSpecs
    {
        [TestFixture]
        public class When_a_logging_service_is_resolved_using_a_static_factory_method
        {
            UnityContainer _container;

            [SetUp]
            public void SetUp()
            {
                _container = new UnityContainer();

                _container
                    .AddNewExtension()
                    .Configure()
                    .RegisterFactory(container =&gt;
                                     LoggingService.GetLoggingService());
            }

            [Test]
            public void A_logging_service_should_be_returned()
            {
                Assert.IsNotNull(_container.Resolve());
            }
        }
    }

    public interface ILoggingService
    {
    }

    public sealed class LoggingService : ILoggingService
    {
        readonly Log4NetLogger _logger;

        LoggingService(Log4NetLogger logger)
        {
            _logger = logger;
        }

        public static ILoggingService GetLoggingService()
        {
            return Nested.instance;
        }

        static class Nested
        {
            internal static readonly ILoggingService instance = new LoggingService(new Log4NetLogger());
        }
    }

    public interface ILogger
    {
    }

    public class Log4NetLogger : ILogger
    {
    }
}
</pre>
<p>While use with actual static factory methods may have been the driving factor for the creation of this extension, there is nothing inherently prescriptive about the extension which necessitates that the methods used be static.</p>
<p>Another example use of the StaticFactoryExtension is to conceal dependencies of resolved types which you may not want to be accessible through the container. Consider the following alternate example registration of the ILoggingService:</p>
<pre class="brush: csharp;">
namespace StaticFactoryExample
{
    public class StaticFactoryExampleSpecs
    {
        [TestFixture]
        public class When_a_logging_service_is_resolved_using_a_static_factory_method
        {
            UnityContainer _container;

            [SetUp]
            public void SetUp()
            {
                _container = new UnityContainer();

                _container
                    .AddNewExtension()
                    .RegisterType(new ContainerControlledLifetimeManager())
                    .Configure()
                    .RegisterFactory(container =&gt;
                                     new LoggingService(new Log4NetLogger()));
            }

            [Test]
            public void A_logging_service_should_be_returned()
            {
                Assert.IsNotNull(_container.Resolve());
            }

            [Test]
            public void The_logging_service_returned_should_always_be_the_same_instance()
            {
                Assert.AreSame(
                    _container.Resolve(),
                    _container.Resolve());
            }
        }
    }

    public interface ILoggingService
    {
    }

    public class LoggingService : ILoggingService
    {
        readonly ILogger _logger;

        public LoggingService(ILogger logger)
        {
            _logger = logger;
        }
    }

    public interface ILogger
    {
    }

    public class Log4NetLogger : ILogger
    {
    }
}
</pre>
<p>In this example, the LoggingService is implemented as a class with an ILogger dependency which must be supplied through the constructor. The factory method responsible for returning the ILoggingService has been rewritten as an expression which returns a newly instantiated instance of the LoggingService and supplies an instance of Log4NetLogger as its dependency implementation. Additionally, the ILoggingService has been registered with a ContainerControlledLifetimeManager. A lifetime manager within Unity is a type responsible for governing how instances of types registered with the container are managed. The ContainerControlledLifetimeManager holds a single instance of the registered type once created and returns the same instance upon all requests. This effectively causes the container to manage the instance as a singleton without placing this responsibility upon the class itself, and without otherwise incurring the drawbacks that the singleton design pattern imposes upon a class.</p>
<p>While enabling the ILoggingService to be resolved by the container could have been achieved without the use of the StaticFactoryExtension by simply registering the LoggingService implementation and the ILogger dependency type, this would have made the instance of ILogger available to types within the system which may not be desired. In this case, the ILoggingService is intended as the public API to be used by types within the system for logging needs. The ILogger type is simply a strategy for how this is accomplished. This approach enables the ILoggingService to be lazy-loaded by the container without exposing the ILogger type.</p>
<p>While the StaticFactoryExtension provides useful behavior to the Unity container, one might argue that the API leaves something to be desired. One of the strengths of the Unity container is its extensibility model. In fact, all of Unity’s functionally is facilitated through extensions. Unfortunately, this means additional functionality such as that provided by the StaticFactoryExtension requires calling the Configure<br />
() method to obtain a reference to the extension. The result is that some degree of ceremony is required each time a factory method needs to be registered for a type.</p>
<p>One approach to improving the API is to encapsulate the required calls to configure a factory method within an extension method. Consider the following extension methods:</p>
<pre class="brush: csharp;">
    public static class UnityExtensions
    {
        public static IUnityContainer RegisterType(this IUnityContainer container, FactoryDelegate factoryMethod)
        {
            container.Configure().RegisterFactory(factoryMethod);
            return container;
        }

        public static IUnityContainer RegisterType(this IUnityContainer container, FactoryDelegate factoryMethod,
                                                   LifetimeManager lifetimeManager)
        {
            container
                .RegisterType(lifetimeManager)
                .Configure().RegisterFactory(factoryMethod);
            return container;
        }
    }
</pre>
<p>In the case of the eariler ILoggingService example, where the desired behavior is to always return the same instance, using the extension method which accepts a FactoryDelegate and a LifetimeManager allows the StaticFactoryExtension behavior to be used as follows:</p>
<pre class="brush: csharp;">
        [SetUp]
        public void SetUp()
        {
            _container = new UnityContainer();

            _container
                .AddNewExtension()
                .RegisterType(container =&gt; new LoggingService(new Log4NetLogger()),
                              new ContainerControlledLifetimeManager());
        }
</pre>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/c9quajfUXnA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/06/unity-static-factory-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/06/unity-static-factory-extension/</feedburner:origLink></item>
		<item>
		<title>Convention-based Registration Extension for Unity</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/zoXx0JJ1dvE/</link>
		<comments>http://www.aspiringcraftsman.com/2009/06/convention-based-registration-extension/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 07:38:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Convention over Configuration]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/06/convention-based-registration-extension-for-unity/</guid>
		<description><![CDATA[Inspired by Jeremy Miller’s presentation of StructureMap’s convention-based type registration at this week’s Austin .Net User’s Group, I set out to create a convention-based type registration extension for the Unity container.
For those unfamiliar with the convention-based approach to type registration for IoC containers, I’ll refer you to Jeremy’s article here which should get you up [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://codebetter.com/blogs/jeremy.miller/">Jeremy Miller</a>’s presentation of <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a>’s convention-based type registration at this week’s <a href="http://www.adnug.org/">Austin .Net User’s Group</a>, I set out to create a convention-based type registration extension for the Unity container.</p>
<p>For those unfamiliar with the convention-based approach to type registration for IoC containers, I’ll refer you to Jeremy’s article <a href="http://codebetter.com/blogs/jeremy.miller/archive/2009/01/20/create-your-own-auto-registration-convention-with-structuremap.aspx">here</a> which should get you up to speed on the concept.</p>
<p>Unity is fairly easy to extend, so I had the first working prototype after about 15 minutes. I spent several hours afterward, however, trying to tease out an API I felt was suitable. After a few cycles attempting to design a fluent API, I settled upon something similar to Fluent NHibernate’s mapping registration, and one which I think fits decently with Unity’s existing API.</p>
<p>Without further ado, here is an example of its usage:</p>
<pre class="brush: csharp;">
        [Concern(&quot;During setup&quot;)]
        public class When_container_configured_with_interface_impl_name_match_convention :
            Behaves_like_context_with_container_with_convention_extension
        {
            protected override void Because()
            {
                _container
                    .Using&lt;IConventionExtension&gt;()
                    .Configure(x =&gt;
                        {
                            x.Conventions.Add&lt;InterfaceImplementionNameMatchConvention&gt;();
                            x.Assemblies.Add(Assembly.GetExecutingAssembly());
                        })
                    .Register();
            }

            [Observation, Test]
            public void Types_matching_convention_should_be_auto_registered()
            {
                _container.Resolve&lt;ITestType&gt;().ShouldBeOfType(typeof (TestType));
            }
        }
</pre>
<p>After adding the extension to the container, the IConventionExtension configuration is used to configure the conventions and assemblies used during the auto-registration process. The convention used here matches the common .Net naming convention where interface and default implementation pairs share the same name, with the interface carrying an ‘I’ prefix. The test demonstrates resolving an instance of ITestType, though no explicit registration has been provided.</p>
<p>The following test demonstrates using an alternate convention where only implementations of the specified type are auto-registered:</p>
<pre class="brush: csharp;">
        [Concern(&quot;During setup&quot;)]
        public class When_container_configured_with_implementation_convention_with_name_replacement :
            Behaves_like_context_with_container_with_convention_extension
        {
            protected override void Because()
            {
                _container
                    .Using&lt;IConventionExtension&gt;()
                    .Configure(x =&gt;
                        {
                            x.Conventions.Add&lt;ImplementationConvention&lt;IController&gt;&gt;();
                            x.Assemblies.Add(Assembly.GetExecutingAssembly());
                        })
                    .Register(x =&gt; x.Replace(&quot;Controller&quot;, &quot;&quot;));
            }

            [Observation, Test]
            public void Controller_types_should_be_resolvable_by_prefix_name()
            {
                _container.Resolve&lt;IController&gt;(&quot;MainView&quot;).ShouldNotBeNull();
            }

            [Observation, Test]
            public void Types_not_of_type_controller_should_not_be_resolvable()
            {
                try
                {
                    _container.Resolve&lt;ITestType&gt;();
                    throw new Exception(&quot;Type ITestType should not be resolvable.&quot;);
                }
                catch (ResolutionFailedException)
                {
                }
            }
        }
</pre>
<p>In this example, the types are registered by name utilizing a delegate to facilitate the ability to modify the default name of the concrete type to be registered in some way. In this case, all implementations of IController are registered under the name of the concrete type, minus the “Controller” suffix.</p>
<p>The full extension source can be downloaded at: <a href="http://code.google.com/p/conventionextension/">http://code.google.com/p/conventionextension/</a>. Enjoy!</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/zoXx0JJ1dvE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/06/convention-based-registration-extension/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/06/convention-based-registration-extension/</feedburner:origLink></item>
		<item>
		<title>Enhancing the Prism Module Initialization Lifecycle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/kINqtVIJleo/</link>
		<comments>http://www.aspiringcraftsman.com/2009/05/enhancing-prism-module-initialization/#comments</comments>
		<pubDate>Sun, 24 May 2009 16:32:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Composite Application Development]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/05/enhancing-the-prism-module-initialization-lifecycle/</guid>
		<description><![CDATA[The Composite Application Library, better known as Prism, is a framework for developing composite-style applications for WPF and Silverlight. Prism facilitates simple module initialization upon application startup, but this is not always adequate for every application. This article discusses an enhanced approach for module initialization within Prism-based applications.
Within Prism, modules are identified by registering types [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://codeplex.com/CompositeWPF">Composite Application Library</a>, better known as Prism, is a framework for developing composite-style applications for WPF and Silverlight. Prism facilitates simple module initialization upon application startup, but this is not always adequate for every application. This article discusses an enhanced approach for module initialization within Prism-based applications.</p>
<p>Within Prism, modules are identified by registering types which implement the IModule interface. This interface defines a single Initialize() method which provides an opportunity to perform any module-level configuration needed by the application. This might include such things as configuring a dependency injection container, registering views with the Region Manager, initializing a module-level <a href="http://msdn.microsoft.com/en-us/library/cc304764.aspx">Application Controller</a>, and other module-level initialization needs.</p>
<p>The IModule interface is defined as follows:</p>
<pre class="brush: csharp;">
    public interface IModule
    {
        void Initialize();
    }
</pre>
<p>While the specifics of module initialization can vary depending upon which dependency injection container (if any) is chosen, the initialization process followed by the UnityBoostrapper provided with Prism iterates over an enumeration of ModuleInfo instances derived from an instance of IModuleCatalog and delegates initialization to an instance of IModuleInitializer for each module. Within the default implementation of IModuleInitializer, the type derived from IModule is retrieved from the ModuleInfo instance, resolved through the Common Service Locator, and the IModule.Initialize() method is invoked on the resolved instance.</p>
<p>The following sequence diagram depicts a simplified view of this process:</p>
<p style="text-align: center;"><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/05/PrismInitSequence.png"><img class="size-full wp-image-51 aligncenter" title="PrismInitSequence" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/05/PrismInitSequence.png" alt="Prism Initialization Sequence" width="913" height="562" /></a></p>
<p>While this process enables basic module initialization, it does not facilitate the ability to initialize modules which may have interdependencies with other modules. One example requiring a multi-phased initialization strategy would be the use of components which initialize application-scoped objects based upon information registered by other modules within the application. For instance, consider an infrastructure module whose purpose is to initialize a database context based upon object-relational mapping information specific to each module. To achieve this within a single-phased initialization strategy, the object-relational mapping information would need to be centralized in one location. This could negatively impact the overall decoupling provided by the Prism framework, and would violate the Open/Closed principle for registering information for newly created modules. With a multi-phased initialization strategy, such a component could register a service used as the object-relational mapping registry, and on a later phase retrieve any registered mapping information to initialize a single database context to be used later by all modules.</p>
<p>One approach to achieving a multi-phased initialization strategy would be to register custom implementations of the Prism types involved in the module initialization process. While this strategy is possible, there are a few disadvantages to this approach.</p>
<p>While many types used within the Prism library enable alternate implementations, the responsibility of initializing modules is not encapsulated by a single type, and the types which encapsulate the module initialization responsibility are not limited to this responsibility alone. To be fair, this statement is only partially true, and only realized upon attempting to replace the assumed single-phased strategy with a multi-phased strategy. The responsibility of initializing each module is assigned to an IModuleInitializer type, but unfortunately alternate implementations are limited to alternate single-phase strategies. This is because the responsibility of iterating over the module metadata resides within the IModuleManager type. Additionally, the methods responsible for iterating over the modules cannot be overridden within a derived type. Providing a new initialization strategy would thus require custom types to be implemented for both interfaces, or for the existing codebase to be modified.</p>
<p>It would be ideal if an alternate initialization strategy could be provided without modifying or rewriting existing framework code, but in lieu this, the existing single-phased strategy can still be leveraged to enable a separate initialization strategy.</p>
<p>While initially considering use of the EventAggregator to raise specific events representing each initialization phase, I chose to encapsulate the phase sequencing responsibilities within an IStagedSequenceService to arrive at a more cohesive, intention revealing, and reusable approach.</p>
<p>The IStagedSequenceService is declared as follows:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Defines a service for providing a staged sequence of events.
    /// &lt;/summary&gt;
    public interface IStagedSequenceService
    {
        void RegisterForStage(Action action, TStageEnum stage);
    }
</pre>
<p>The purpose of this interface is to allow components to register an Action delegate to be associated with a supplied generic enumeration stage.</p>
<p>The implementation of the IStagedSequenceService is declared as follows:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Provides the default implementation for &lt;see cref=&quot;IStagedSequenceService&quot;/&gt;.
    /// &lt;/summary&gt;
    public class StagedSequenceService : IStagedSequenceService
    {
        readonly List[] stages;

        public StagedSequenceService()
        {
            stages = new List[NumberOfEnumValues()];

            for (int i = 0; i &lt; stages.Length; ++i)
            {
                stages[i] = new List();
            }
        }

        public virtual void ProcessSequence()
        {
            foreach (var stage in stages)
            {
                foreach (var action in stage)
                {
                    action();
                }
            }
        }

        public virtual void RegisterForStage(Action action, TStageEnum stage)
        {
            stages[Convert.ToInt32(stage)].Add(action);
        }

        int NumberOfEnumValues()
        {
            return typeof (TStageEnum).GetFields(BindingFlags.PublicBindingFlags.Static).Length;
        }
    }
</pre>
<p>This implementation initializes a two-dimensional array based upon the number of stages in a sequence (i.e. the number of enumeration values representing the stages). The implementation of the RegisterForStage() method is then able to store each registered Action delegate in the appropriate collection for each stage. A ProcessSequence() method is supplied with a simple two-level loop which executes the registered delegates for each stage.</p>
<p>Next, an enumeration type is required to define the desired stages for the application:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// Defines stages used by modules requiring staged initialization.
    /// &lt;/summary&gt;
    public enum ModuleInitializationStage
    {
        /// &lt;summary&gt;
        /// The preinitialization stage is used to perform initialization
        /// required before external module initialization.
        /// &lt;/summary&gt;
        PreInitialization,

        /// &lt;summary&gt;
        /// The initialization stage is used to perform
        /// initialization required by the current module.
        /// &lt;/summary&gt;
        Initialization,

        /// &lt;summary&gt;
        /// The post-initialization stage is used to perform
        /// initialization required after external module initialization.
        /// &lt;/summary&gt;
        PostInitialization,

        /// &lt;summary&gt;
        /// The startup stage is used to perform perform initial
        /// tasks after all initialization is complete.
        /// &lt;/summary&gt;
        StartUp
    }
</pre>
<p>Next, an IModuleInitializationService and implementation is defined specifying the ModuleInitializationStage enumeration:</p>
<pre class="brush: csharp;">
    public interface IModuleInitializationService : IStagedSequenceService
    {
    }

    public class ModuleInitializationService : StagedSequenceService, IModuleLifecycleService
    {
        public virtual void Initialize()
        {
            base.ProcessSequence();
        }
    }
</pre>
<p>An Initialize() method is provided to wrap the ProcessSequence call. This is done to provide a more meaningful API to the specific context for this manifestation of the IStagedSequenceService.</p>
<p>To provide the base implementation required to take advantage of the new staged-initialization capabilities, a ModuleBase abstract class is defined which registers a protected virtual method corresponding to each of the defined stages:</p>
<pre class="brush: csharp;">
    public abstract class ModuleBase : IModule
    {
        public void Initialize()
        {
            var moduleLifecycleService = ServiceLocator.Current.GetInstance();

            moduleLifecycleService.RegisterForStage(OnPreInitialization, ModuleInitializationStage.PreInitialization);

            moduleLifecycleService.RegisterForStage(OnInitialization, ModuleInitializationStage.Initialization);

            moduleLifecycleService.RegisterForStage(OnPostInitialization, ModuleInitializationStage.PostInitialization);

            moduleLifecycleService.RegisterForStage(OnStartUp, ModuleInitializationStage.StartUp);
        }

        protected virtual void OnPreInitialization()
        {
        }

        protected virtual void OnInitialization()
        {
        }

        protected virtual void OnPostInitialization()
        {
        }

        protected virtual void OnStartUp()
        {
        }
    }
</pre>
<p>To drive the new initialization strategy, the new ModuleInitializationSerivce is registered with the container and the UnityBootstrapper.InitializeModules() method is overridden in the main bootstrapper class to invoke the service’s Initialize() method:</p>
<pre class="brush: csharp;">
    public class DesktopBootstrapper : UnityBootstrapper
    {
        // other methods

        protected override void ConfigureContainer()
        {
            _moduleInitializationService = new ModuleInitializationService();

            Container.RegisterInstance(_moduleInitializationService, new ContainerControlledLifetimeManager());

            // other configuration
        }

        protected override void InitializeModules()
        {
            base.InitializeModules();
            _moduleInitializationService.Initialize();
        }
    }
</pre>
<p>From here, modules requiring participation within the staged-initialized strategy need only implement the abstract ModuleBase class and override the appropriate method based upon the specific scenario required:</p>
<pre class="brush: csharp;">
    public class ExampleModule : ModuleBase
    {
        protected override void OnPreInitialization()
        {
            // TODO Register services required by other modules.
        }

        protected override void OnInitialization()
        {
            // TODO perform initialization requiring services from other modules.
        }
    }
</pre>
<p>In conclusion, while the Composite Application Library does not provide a multi-phased initialization strategy, this can still be achieved by leveraging the existing behavior to facilitate a new strategy.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/kINqtVIJleo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/05/enhancing-prism-module-initialization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/05/enhancing-prism-module-initialization/</feedburner:origLink></item>
		<item>
		<title>Implementing INotifyProperyChanged  with Unity Interception</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/-_gve0Xje5s/</link>
		<comments>http://www.aspiringcraftsman.com/2009/03/implementing-inotifyproperychanged-with/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 09:32:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2009/03/implementing-inotifyproperychanged-with-unity-interception/</guid>
		<description><![CDATA[Inspired by Sebastien Lambla&#8217;s post, Implementing INotifyPropertyChanged with DynamicProxy2, I decided to provide an example of how INotifyPropertyChanged can be implemented using Unity&#8217;s new interception capabilities.
Prolegomena
While not necessary for using the Unity container, some may find a basic understanding of how Unity works to be helpful when registering objects for interception or using other capabilities [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by Sebastien Lambla&#8217;s post, <a href="http://serialseb.blogspot.com/2008/05/implementing-inotifypropertychanged.html">Implementing INotifyPropertyChanged with DynamicProxy2</a>, I decided to provide an example of how <a href="http://msdn.microsoft.com/en-%20%%20%2020us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged </a>can be implemented using Unity&#8217;s new <a href="http://msdn.microsoft.com/en-us/library/dd140045.aspx">interception capabilities</a>.</p>
<h2>Prolegomena</h2>
<p>While not necessary for using the Unity container, some may find a basic understanding of how Unity works to be helpful when registering objects for interception or using other capabilities of Unity.</p>
<p>The Unity container is best understood as a façade for a highly configurable, yet complex object factory named named Object Builder. Object Builder made its debut within the <a href="http://msdn.microsoft.com/en-us/library/aa480450.aspx">Composite UI Application Block</a> in November 2005 and was subsequently incorporated into <a href="http://msdn.microsoft.com/en-us/library/cc467893.aspx">Enterprise Library 2.0</a> with its January 2006 release as its internal configuration strategy.</p>
<p>At its core, Object Builder is based upon the <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain-of-Responsibility</a> pattern. The Object Builder chain-of-responsibility utilizes two primary concepts for configuring how objects are constructed: namely, Strategies and Policies. Strategies serve as the concrete handlers within the chain-of-responsibility implementation, and are the objects which encapsulate the behavior performed during the construction process. Policies serve as the rules for how and when Strategies apply to a given type. Strategies and Policies are the essence of Object Builder&#8217;s extensibility, and by extension Unity&#8217;s extensibility.</p>
<p>While Object Builder can be used directly to provide advanced dependency injection and other inversion of control needs, due to the fact that it waswritten to serve the internal needs of the guidance assets provided by the Microsoft Patterns &amp; Practices group, it wasn&#8217;t developed with ease of use in mind and didn&#8217;t provide the same API nomenclature used by other containers. This is where Unity comes in.</p>
<p>Unity was written to provide an easy to use and more traditional container interface to Object Builder. Part of this interface includes a more simplified end-user extensibility API in the form of Unity Extensions. These extensions encapsulate the lower-level Strategy and Policy configuration for Object Builder.</p>
<p>The 1.2 release of Unity in October 2008 included a new extension for facilitating aspect-oriented programming through method interception. The remainder of this article demonstrates how this new extension can be used to implement the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged </a>interface.</p>
<h2>Interception Example</h2>
<p>To start, we&#8217;ll create a test fixture skeleton to drive our example:</p>
<pre class="brush: csharp;">
    [TestFixture]
    public class When_model_property_changes
    {
        [SetUp]
        public void SetUp()
        {
            EstablishContext();
            Because();
        }

        protected override void EstablishContext()
        {
        }

        protected override void Because()
        {
        }

        [Test]
        public void A_notify_property_changed_event_should_be_raised()
        {
        }
    }
</pre>
<p>Next, we&#8217;ll establish the context of our test by configuring an instance of the Unity container to intercept methods for a type named IModel:</p>
<pre class="brush: csharp;">
    [TestFixture]
    public class When_model_property_changes : ContextSpecification
    {
        IUnityContainer container;
        IModel model;

        /** snip **/

        protected void EstablishContext()
        {
            container = new UnityContainer();

            container.AddNewExtension()
                .RegisterType&lt;IModel, Model&gt;()
                .Configure()
                .SetDefaultInterceptorFor&lt;IModel&gt;(new TransparentProxyInterceptor());

            model = container.Resolve&lt;IModel&gt;();
        }

        /** snip **/
    }
</pre>
<p>We configure our container by first adding the Interception extension. Next, we register the type we will be resolving from the container. Finally, we set a default interceptor for our type.<br />
By adding the Interception extension, two new build strategies are added to the chain-of-responsibility for facilitating interception. Additionally, the extension registers an instance of an AttributeDrivenPolicy which is used by the interception strategies to provide the ability to identify which methods should be intercepted through the use of attributes. We will later create a custom attribute derived from HandlerAttribute which will match our type with the AttributeDrivenPolicy.</p>
<p>Note: The AttributeDrivenPolicy is a policy type internal to the Interception extension and is not related to the<br />
IBuilderPolicy types used by the Object Builder component.</p>
<p>Our last step in establishing the context for our test is to have the container create an instance of our registered type.</p>
<p>Next, we&#8217;ll define the behavior of our test to be observed:</p>
<pre class="brush: csharp;">
        protected override void Because()
        {
            model.PropertyChanged += (sender, args) =&gt; { propertyChangedEventRaised = true; };
            model.TestProperty = &quot;[any value]&quot;;
        }
</pre>
<p>Here, we establish that the model should have a public event named PropertyChanged and a public writable string member named TestProperty. When the event is fired, we&#8217;ll set a Boolean named propertyChangedEventRaised to true which we&#8217;ll test for later in our observation.</p>
<p>Our next step is to go ahead and create the types we&#8217;ve registered with the container and declare our propertyChangedEventRaised Boolean member:</p>
<pre class="brush: csharp;">
    [TestFixture]
    public class When_model_property_changes
    {
        IUnityContainer container;
        IModel model;
        bool propertyChangedEventRaised;

        internal interface IModel : INotifyPropertyChanged
        {
            string TestProperty { get; set; }
        }

        internal class Model : IModel
        {
            public string TestProperty { get; set; }
            public event PropertyChangedEventHandler PropertyChanged;
        }

        /** snip **/
    }
</pre>
<p>Notice that we currently have no code within the Model type to actually raise the PropertyChanged event.</p>
<p>Next, we need to provide the observation portion of our test:</p>
<pre class="brush: csharp;">
        bool propertyChangedEventRaised;

        [Test]
        public void Should_raise_notify_property_changed_event()
        {
            Assert.That(propertyChangedEventRaised, Is.True);
        }
</pre>
<p>Running the test at this point produces the expected failure result:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/03/unity_interception_nunit_fail.png"><img class="aligncenter size-full wp-image-54" title="unity_interception_nunit_fail" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/03/unity_interception_nunit_fail.png" alt="" width="946" height="248" /></a></p>
<p>To make the test pass, we need to configure our type to match an interception policy and provide an interception handler which will raise the</p>
<p>PropertyChanged event on behalf of our type. Since we&#8217;re using the default AttributeDrivenPolicy to have the interception strategies recognize our type as one to be intercepted, we need to create an attribute derived from the extension&#8217;s HandlerAttribute:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// This attribute is used to denote that the event is to be intercepted.
    /// &lt;/summary&gt;
    public class NotifyAttribute : HandlerAttribute
    {
        readonly ICallHandler handler;

        public NotifyAttribute()
        {
            handler = new NotifyPropertyChangedCallHandler();
        }

        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return handler;
        }
    }
</pre>
<p>The HandlerAttribute is used by the AttributeDrivenPolicy to return an ICallHandler. The ICallHandler type encapsulates the behavior used to intercept method calls for the configured types within Unity. Here, we return a NotifyPropertyChangedCallHandler() which will intercept all call to methods adorned with our custom attribute.</p>
<p>Next, we create our NotifyPropertyChangedCallHandler to raise the PropertyChanged event for our property:</p>
<pre class="brush: csharp;">
    /// &lt;summary&gt;
    /// This class handler is used in conjunction with Unity to handle INotifiyPropertyChanged
    /// implementations as an aspect.
    /// &lt;/summary&gt;
    class NotifyPropertyChangedCallHandler : ICallHandler
    {
        public int Order
        {
            get { return 0; }
            set { }
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result = getNext.Invoke().Invoke(input, getNext);
            MethodBase method = input.MethodBase;

            if (method.IsSpecialName &amp;&amp; method.Name.StartsWith(&quot;set_&quot;))
            {
                // Get the property name
                string propertyName = method.Name.Substring(4);

                // Get the private event backing field
                FieldInfo info = input.Target.GetType()
                    .GetFields(BindingFlags.InstanceBindingFlags.NonPublic)
                    .Where(f =&gt; f.FieldType == typeof (PropertyChangedEventHandler))
                    .FirstOrDefault();

                if (info != null)
                {
                    var handler = info.GetValue(input.Target) as PropertyChangedEventHandler;

                    // Ensure subscriptions
                    if (handler != null)
                    {
                        handler.Invoke(input.Target, new PropertyChangedEventArgs(propertyName));
                    }
                }
            }

            return result;
        }
    }
</pre>
<p>Finally, we need to add our custom attribute to the property of our type for which we want our interception to occur:</p>
<pre class="brush: csharp;">
    internal class Model : IModel
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public string TestProperty { get; [Notify] set; }
    }
</pre>
<p>Running our test again shows that it now passes!</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/03/unity_interception_nunit_pass.png"><img class="aligncenter size-full wp-image-55" title="unity_interception_nunit_pass" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2009/03/unity_interception_nunit_pass.png" alt="" width="790" height="231" /></a></p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/-_gve0Xje5s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2009/03/implementing-inotifyproperychanged-with/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2009/03/implementing-inotifyproperychanged-with/</feedburner:origLink></item>
		<item>
		<title>Examining the Dependency Inversion Principle</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/nseUsRPq_cU/</link>
		<comments>http://www.aspiringcraftsman.com/2008/12/examining-dependency-inversion/#comments</comments>
		<pubDate>Sun, 28 Dec 2008 16:53:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Dependency Inversion Principle]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2008/12/examining-the-dependency-inversion-principle/</guid>
		<description><![CDATA[Introduction
A hallmark of good solution architecture is the degree of low-coupling between the components comprising an application. One design strategy first postulated by Robert C. Martin for decoupling components within object-oriented systems is the Dependency Inversion Principle. This article provides an introduction to this principle, considers its relationship to other software patterns and practices, and [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>A hallmark of good solution architecture is the degree of low-coupling between the components comprising an application. One design strategy first postulated by Robert C. Martin for decoupling components within object-oriented systems is the Dependency Inversion Principle. This article provides an introduction to this principle, considers its relationship to other software patterns and practices, and reflects on the merits of adhering to this principle.</p>
<h2>Overview</h2>
<p>The Dependency Inversion Principle is defined as follows:</p>
<p style="padding-left: 30px;"><em>A. High-level modules should not depend upon low-level modules. Both should depend upon abstractions.</em></p>
<p style="padding-left: 30px;"><em>B. Abstractions should not depend upon details. Details should depend upon abstractions.</em></p>
<p>In conventional architecture, higher-level components depend upon lower-level components as depicted in the following diagram:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP1.png"><img class="aligncenter size-full wp-image-58" title="DIP1" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP1.png" alt="" width="433" height="313" /></a></p>
<p>In this diagram, component A depends upon component B, which in turn depends upon component C. Due to these dependencies, each of the higher-level components is coupled with the lower-level components.</p>
<p>The goal of the Dependency Inversion Principle is to decouple higher-level components from their dependency upon lower-level components. This may be achieved by creating interfaces as part of the higher-level component package which define the component’s external needs. This allows the component to be isolated from any particular implementation of the provided interface, thus increasing the component’s portability. The following diagram illustrates this relationship:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP2.png"><img class="aligncenter size-full wp-image-59" title="DIP2" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP2.png" alt="" width="531" height="559" /></a></p>
<p>In this diagram, component A provides an interface which defines the services it needs. Component B satisfies this dependency by implementing the interface. The same relationship is additionally shown for components B and C. Take special note that the interfaces are packaged together with the higher-level components and are defined in terms of the higher-level component’s needs, not the lower-level component’s behavior. It is this association of the interface with the client component which logically inverts the conventional dependency flow.</p>
<p>In some cases, multiple higher-level components existing in separate packages share similar external dependency needs which would best be satisfied by a single lower-level component. In this case, the Dependency Inversion Principle requires that clients agree upon the desired interface which is then published in a separate package. The following diagram illustrates this relationship:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP3.png"><img class="aligncenter size-full wp-image-60" title="DIP3" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP3.png" alt="" width="713" height="570" /></a></p>
<p>In this diagram, components A and B share a dependency upon a single package containing the common client interface. Component C implements this interface, thus satisfying the dependency of both higher-level components. Note again that the interface here is defined according to the shared needs of the higher-level components rather than according to the behavior provided by the lower-level component. According to the Dependency Inversion Principle, the higher-level components share the ownership of the separate interface package. While in some situations this will arguably be a nominal distinction to make, especially when all of the components are to be maintained by the same development group, this distinction logically maintains the guideline that higher-level components shouldn’t depend upon lower-level components. When the components are maintained by separate groups, this distinction may have implications on which groups are consulted if changes to the interface become necessary. Additionally, the association of the interface with the higher-level component(s) may in some cases impact the style and naming conventions used in the creation of the interface. However, when all components are maintained by the same group, this can indeed become a distinction without a difference.</p>
<p>The second, seemingly more peculiar aspect of the Dependency Inversion Principle is the stipulation that abstractions should not depend upon details, but rather that details should depend upon abstractions. To fully understand the motivation behind this portion of the principle, it is helpful to understand from wince this principle was derived.</p>
<p>The Dependency Inversion Principle was first conceived within the context of C++ development. In the C++ language, classes are typically defined using both a declaration source file and a definition source file. The declaration source files are referred to as header files and are primarily used for including the necessary class declarations required by other components at compile time. While header files provide a measured form of abstraction in C++, their purpose is not to provide separation of interface from implementation. Header files define all the public and private member functions for a class definition, as well as any member variables used by the class. Due to the fact that header files contain implementation details about the class definition, header files (i.e. the abstraction) are dependent upon the source files (i.e. the detail).</p>
<p>While the C++ language does not define an interface type as a first class entity (as is the case in languages such as Java and C#), it does support the notion of a pure abstract class. A pure abstract class is one which contains only abstract methods and which is devoid of any data. Through the use of pure abstract classes, interfaces can be defined to enforce contracts between components. It is the contrast between the use of header files and the use of pure abstract classes (i.e. interfaces) that is in view when the Dependency Inversion Principle advises that abstractions should not depend upon details, but that details should depend upon abstractions.</p>
<p>The next sections will discuss several other associated patterns and practices related to achieving low coupling between components to further aid in the understanding of the Dependency Inversion Principle.</p>
<h2>Dependency Inversion and Plain Ole Interfaces</h2>
<p>One practice often confused with the Dependency Inversion Principle is the fundamental practice of programming to interfaces rather than implementations.</p>
<p>A fairly common description of the Dependency Inversion Principle establishes a base line example demonstrating components which are tightly coupled as<br />
in the following diagram:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP4.png"><img class="aligncenter size-full wp-image-61" title="DIP4" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP4.png" alt="" width="289" height="205" /></a></p>
<p>A second example is then typically shown with the introduction of an interface to decouple the dependency between the components as in the following diagram:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP5.png"><img class="aligncenter size-full wp-image-62" title="DIP5" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP5.png" alt="" width="333" height="259" /></a></p>
<p>While programming to interfaces rather than implementations represents good design practice, the Dependency Inversion Principle is not merely concerned with the use of interfaces, but the decoupling of high-level components from dependency packages. All that has been demonstrated in the above example is the introduction of an abstraction to the dependency. If this abstraction is contained within the dependency package, the high-level component is still coupled to the low-level component’s package. While the conventional use of interfaces adhere to the guideline that abstractions should not depend upon details (a somewhat vestigial guideline from the perspective of languages such as Java and C#), inversion of the conventional dependency relationship is not achieved unless the high-level component defines its own interface whose implementations are defined in separate packages.</p>
<p>Simply stated, every case of programming to interfaces rather than implementations are not examples of the Dependency Inversion Principle.</p>
<h2>Dependency Inversion and the Separated Interface Pattern</h2>
<p>The Separated Interface Pattern, defined in the book Patterns of Enterprise Application Architecture, sets forth an approach for decoupling components from the implementation details of their dependencies. This is accomplished by defining the interface of the dependency in a separate package from its implementation. One illustration given in the book for how this might be achieved places the interface within the client component package as depicted in the following diagram:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP6.png"><img class="aligncenter size-full wp-image-63" title="DIP6" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP6.png" alt="" width="351" height="359" /></a></p>
<p>An alternate approach of storing the interface in its own package is also presented, and is recommended when the dependency is used by multiple clients. The following diagram depicts this organization:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP7.png"><img class="aligncenter size-full wp-image-64" title="DIP7" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP7.png" alt="" width="592" height="378" /></a></p>
<p>As one might observe, these diagrams bear a striking resemblance to the structures advocated by the Dependency Inversion Principle. This similarity has led some to consider the two to be synonymous, and to a large extent they are. However, while the organization of the components set forth by each is nearly identical, slight nuances exists between the advocacy and description set forth by each approach.</p>
<p>First, while both have in view the decoupling of components from the implementation details of their dependencies, the Dependency Inversion Principle achieves this by assigning ownership of the interface to the higher-level component, whereas the Separated Interface pattern achieves this by separating the interface from the implementation … irrespective of any assumed package ownership.</p>
<p>The distinction is the level of emphasis placed by the Dependency Inversion Principle on the value in reusing higher-level components over that of lower-level components. While such an approach is facilitated by the Separated Interface pattern, no such value assignments are assumed.</p>
<p>Additionally, because the Dependency Inversion Principle assigns ownership of the interface to the higher-level component, it considers interfaces more closely aligned with their clients than with their implementations. The Separated Interface pattern makes no assumption on who should own the interface. In fact, the book Patterns of Enterprise Application Architecture sets forth that one reason for separating an interface into a separate package is when there is a desire for emphasizing that the development of the interface isn’t the responsibility of the client developers.</p>
<p>The Separated Interface pattern does set forth the option of packaging the interface with the client, especially when there is only one client, or all the clients are maintained in the same package, but this is more a matter of pragmatism than principle. In similar fashion, the Dependency Inversion Principle acknowledges situations where there may be no particular owner to an interface. This, however, is set forth more as a special case than the general prescription.</p>
<p>Another nuance is the level of applicability advocated by each approach. The Dependency Inversion Principle declares that higher-level components should never depend upon lower-level components. In contrast, the Separated Interface pattern advocates a more conservative approach, even advising against introducing the complexity of separating interface from implementation prematurely, favoring rather to keep interface and implementation together until a specialized need arises.</p>
<p>While both the Dependency Inversion Principle and the Separated Interface pattern result in nearly identical arrangements of the components involved, each approach the same problem with slightly different perspectives and advocate different levels of applicability.</p>
<h2>Dependency Inversion and Dependency Injection</h2>
<p>Another practice often associated with the Dependency Inversion Principle is Dependency Injection. Dependency Injection encompasses a set of techniques for assigning the responsibility of provisioning dependencies for a component to an external source. The goal of Dependency Injection is to separate the concerns of how a dependency is obtained from the core concerns of a component.</p>
<p>One dependency injection technique, referred to as constructor injection, defines the dependencies of a component within its constructor which are supplied at the time of the component’s creation. A simple demonstration of this technique can be seen in the following code example where an instance of an Automobile class is obtained which has a dependency upon an Engine class:</p>
<pre class="brush: csharp;">
    public class Application
    {
        public void CreateAutomobile()
        {
            var automobile = new Automobile(new Engine());
        }
    }

    public class Automobile
    {
        Engine _engine;

        public Automobile(Engine engine)

        {
            _engine = engine;
        }

        // ...
    }

    public class Engine
    {
        // ...
    }
</pre>
<p>In this example, an instance of Automobile is created by passing an instance of a newly created Engine to the Automobile class constructor. This decouples how the Engine is created from the core concerns of the Automobile class. Dependency injection is typically accompanied by the use of interfaces to decouple the dependency from its implementation and is generally facilitated through an Inversion of Control framework to construct complex object graphs. The use of interfaces has been omitted here for clarity, but also to help emphasis that dependency injection is concerned with decoupling how dependencies are obtained, not the abstraction of dependencies.</p>
<p>The practice of dependency injection is often discussed alongside the Dependency Inversion Principle as a facilitating pattern for supplying implementations of the client interface to the client component at run time. While other patterns such as Service Locator and Plug-in can be used to facilitate the Dependency Inversion Principle, Inversion of Control in the more common solution due to its ability to decouple components from how their dependencies are obtained.</p>
<p>One potential stumbling block newcomers to these design approaches face is in the similarity of terms used in describing these approaches. For instance, taken at face value, the phrase “Dependency Inversion” might conjure up the idea that dependency requirements are being inverted (as in turned inside out) rather than the inversion of dependency (as in reversal) between higher-level components and lower-level components. While the former is an adequate understanding of what dependency injection is, it doesn’t describe the goal of the Dependency Inversion Principle. While certainly complimentary, how dependency implementations are obtained is orthogonal to the module dependency concerns set forth by the Dependency Inversion Principle.</p>
<p>Benefits and Consequences<br />
The approach advocated by the Dependency Inversion Principle provides a useful option for decoupling components from their external dependencies. By following the guideline that higher-level components shouldn’t depend upon lower-level components, core functionality within an application can be more easily used in different contexts.</p>
<p>While applying the Dependency Inversion Principle enables higher-level components to be used in a different context, it unfortunately negatively impacts the ability to reuse lower-level components. While this may at times be an optimal compromise, it is not always the case that higher-level components possess the greatest need for decoupling.</p>
<p>The core business components within an application often encapsulate a rich set of behavior tailored to a specific context. While such components may be of tremendous benefit to applications requiring the same behavior, it is their specificity that tends to limit the context where reuse is possible. In contrast, lower-level components often encapsulate more generic functionality which is applicable across a wider range of contexts.</p>
<p>Consider for example the development of a custom logging component. Logging is generally a concern shared by many components across all applications within an enterprise. In following the Dependency Inversion Principle, the logging component would be developed to depend upon a client-owned interface package to allow higher-level components to remain decoupled from the specific logging implementation. While this enables a higher-level component to be reused without requiring the specific logging implementation, it doesn’t allow the logging component to be easily used by other applications.</p>
<p>While the Dependency Inversion Principle does account for the reuse of lower-level components by maintaining the client interface in a separate package, assigning ownership of this package to one or more consumers of a lower-level component can itself be problematic. In doing so, this creates a form of associative coupling between clients which may have diverging interests that affect the agreement upon, or stability of the interface contract. Additionally, the resulting contract, naming conventions, and deployment strategy may lack the objectively and elegance that might follow more naturally from assigning the ownership of the interface package to the lower-level component.</p>
<h2>An Alternate Approach</h2>
<p>In considering the logging example further, an alternate approach to coupling either component package to the other is the combination of the Separated Interface pattern with the Adapter pattern to allow both higher-level and lower-level components to exist independently.</p>
<p>Through this approach, an interface to the dependency is maintained within the high-level component package (or in a separate package shared among two or more high-level components), but an additional adapter package is created to adapt the interface of the high-level component to that of the low-level component.</p>
<p>The following diagram illustrates this organization:</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP8.png"><img class="aligncenter size-full wp-image-65" title="DIP8" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/12/DIP8.png" alt="" width="713" height="579" /></a></p>
<p>By using a logging adapter to implement the client-owned interface, both the high-level client components and the logging component are able to remain free from dependency upon one another. While this approach dispenses with the notion of dependency inversion from the low-level component point of view, it achieves the Dependency Inversion principle’s goal of decoupling without affecting the potential reuse of lower-level components. Though this level of decoupling is certainly not necessary in every case, this technique offers a more flexible option for those wishing to maximize the level of decoupling between application and infrastructure components.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/nseUsRPq_cU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2008/12/examining-dependency-inversion/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2008/12/examining-dependency-inversion/</feedburner:origLink></item>
		<item>
		<title>Model View Presenter Styles</title>
		<link>http://feedproxy.google.com/~r/AspiringCraftsman/~3/7BIDrYqKR_k/</link>
		<comments>http://www.aspiringcraftsman.com/2008/11/model-view-presenter-styles/#comments</comments>
		<pubDate>Sun, 23 Nov 2008 19:13:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Model-View-Presenter]]></category>

		<guid isPermaLink="false">http://www.aspiringcraftsman.com/2008/11/model-view-presenter-styles/</guid>
		<description><![CDATA[Introduction
The Model-View-Presenter pattern is an interactive application architecture pattern used to separate the concerns of an application’s data, presentation, and user input into specialized components. The article Interactive Application Architecture Patterns includes an introduction to the MVP pattern along with discussion of its history and pattern variations. In addition to the variations discussed therein, there [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>The Model-View-Presenter pattern is an interactive application architecture pattern used to separate the concerns of an application’s data, presentation, and user input into specialized components. The article <a href="/2007/08/interactive-application-architecture.html">Interactive Application Architecture Patterns</a> includes an introduction to the MVP pattern along with discussion of its history and pattern variations. In addition to the variations discussed therein, there also exists variation in how the pattern may be implemented. This article presents three styles for implementing the Model-View-Presenter pattern.</p>
<h2>The Encapsulated Presenter Style</h2>
<p>The first of the styles considered here is what might be called the Encapsulated Presenter style. Following this style, the Presenter exists as an implementation detail of the View. The Presenter responds to event notifications from the Model, but is known only to the View to which it is assigned and consequently is only accessed directly by the View.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/EncapsulatedPresenter.png"><img class="aligncenter size-full wp-image-70" title="EncapsulatedPresenter" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/EncapsulatedPresenter.png" alt="" width="467" height="351" /></a></p>
<p>Other components within the system requiring view-related data and/or behavior encapsulated within the Presenter will request access through a reference to the View. This results in consistent access to the encapsulated data and behavior, regardless of whether the access is triggered through the user interface or by other components within the system. One practical benefit gained through this approach is the ability to change the particular pattern used to segment presentation logic without affecting other components within the system. For instance, an application initially designed to use the Supervising Controller or Passive View variations of the MVP pattern may later be refactored to encapsulate both data and behavior using the Presentation Model pattern.</p>
<p>The following example demonstrates the Encapsulated Presenter style:</p>
<pre class="brush: csharp;">
    public interface IView
    {
        string Text { get; set; }

        void Show();
    }

    public class View : IView
    {
        Presenter presenter;

        public View() : this(new Presenter())
        {
        }

        public View(Presenter presenter)
        {
            this.presenter = presenter;
            presenter.View = this;
        }

        #region IView Members

        public string Text { get; set; }

        public void Show()
        {
            presenter.OnShow();

            Console.WriteLine(&quot;Current Time: &quot; + Text);
        }

        #endregion

        protected void Button_Click(object sender, EventArgs e)
        {
            presenter.OnButtonClick();
        }
    }

    public class Presenter
    {
        IModel model;

        public Presenter() : this(new Model())
        {
        }

        public Presenter(IModel model)
        {
            this.model = model;
            model.TextChanged += new EventHandler(model_TextChanged);
        }

        public IView View { get; set; }

        void model_TextChanged(object sender, EventArgs e)
        {
            View.Text = model.Text;
        }

        internal void OnButtonClick()
        {
            model.Text = &quot;Button Clicked&quot;;
        }

        internal void OnShow()
        {
            // Update view when shown
            View.Text = model.Text;
        }
    }

    public interface IModel
    {
        string Text { get; set; }
        event EventHandler TextChanged;
    }

    public class Model : IModel
    {
        string text;

        public event EventHandler TextChanged = delegate { };

        public string Text
        {
            get { return text ?? (text = DateTime.Now.ToString()); }

            set
            {
                text = value;
                TextChanged(this, EventArgs.Empty);
            }
        }
    }
</pre>
<p>In this example, a View provides constructors for being instantiated with either a default or provided instance of the Presenter. The View then sets its private Presenter instance used later for delegation and sets the Presenter’s View property to itself. The View also contains a Button_Click() event handler representing the initial interceptor for a button control. When invoked, this handler delegates control to the Presenter.OnButtonClick() method.</p>
<p>The Presenter likewise provides constructors for being instantiated with either a default or provided instance of the Model and registers to receive event notifications when the Model changes. When notified, the Presenter updates the Text property of the View.</p>
<p>The following is a test for the presentation logic contained within the Presenter:</p>
<pre class="brush: csharp;">
    [TestClass]
    public class ViewTest
    {
        [TestMethod]
        public void PresenterShouldUpdateViewOnModelChange()
        {
            var model = new Model {Text = &quot;Initial value&quot;};
            var view = new StubView();
            var presenter = new Presenter(model);
            presenter.View = view;
            model.Text = &quot;Changed value&quot;;
            Assert.AreEqual(view.Text, &quot;Changed value&quot;);
        }
    }

    class StubView : IView
    {
        public string Text { get; set; }

        public void Show()
        {
        }
    }

The following code snippet demonstrates how a View might be accessed using the Encapsulated Presenter style:

    class Program
    {
        static void Main(string[] args)
        {
            // Show the view
            var view = new View();
            view.Show();

            // Retrieve the view state
            string text = view.Text;

            Console.WriteLine(&quot;View text: &quot; + text);
            Console.ReadKey(true);
        }
    }
</pre>
<h2>The Encapsulated View Style</h2>
<p>The next style considered will be referred to here as the Encapsulated View style. Following this style, the Presenter serves as an interface to view-related data and behavior accessed by other components within the application. In addition to decoupling the presentation logic from the View, this assigns a form of Page Controller responsibility to the Presenter. As with Page Controller, the Presenter in this style provides input control for views when accessed by other components.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/EncapsulatedView.png"><img class="aligncenter size-full wp-image-71" title="EncapsulatedView" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/EncapsulatedView.png" alt="" width="476" height="350" /></a></p>
<p>While the View continues to delegate user input requests to the Presenter, other components within the system interact with view-related data and/or behavior through a reference to the Presenter. One of the benefits of this approach is that it eliminates the need to expose delegating properties or methods on the View which are not otherwise required by the user interface. For example, given a View which presents a selection dialog of mailing addresses associated with a specific customer, this approach would allow other components to call a method directly on the Presenter to display the selection for a given customer number. By allowing access to the Presenter directly, the View interface is free from the need of exposing any properties or methods not directly concerned with the visual display of the application.</p>
<p>The following example demonstrates the Encapsulated View style using an explicit delegation approach:</p>
<pre class="brush: csharp;">
    public interface IView
    {
        IPresenter Presenter { get; set; }
        string Text { get; set; }
        void Show();
    }

    public class View : IView
    {
        public View()
        {
        }

        public IPresenter Presenter { get; set; }
        public string Text { get; set; }

        public void Show()
        {
            Console.WriteLine(&quot;Current Time: &quot; + Text);
        }

        protected void Button_Click(object sender, EventArgs e)
        {
            Presenter.OnButtonClick();
        }
    }

    public interface IPresenter
    {
        string Text { get; set; }
        void ShowView();
        void OnButtonClick();
    }

    public partial class Presenter : IPresenter
    {
        IModel model;
        IView view;

        public Presenter() : this(new View(), new Model())
        {
        }

        public Presenter(IView view) : this(view, new Model())
        {
        }

        public Presenter(IView view, IModel model)
        {
            this.view = view;
            this.model = model;
            view.Presenter = this;
            model.TextChanged += new EventHandler(model_TextChanged);
        }

        public string Text
        {
            get { return view.Text; }

            set { view.Text = value; }
        }

        public void OnButtonClick()
        {
            model.Text = &quot;Button Clicked&quot;;
        }

        public void ShowView()
        {
            // Update view when shown
            view.Text = model.Text;
            view.Show();
        }

        void model_TextChanged(object sender, EventArgs e)
        {
            view.Text = model.Text;
        }
    }

    public interface IModel
    {
        string Text { get; set; }
        event EventHandler TextChanged;
    }

    public class Model : IModel
    {
        string text;
        public event EventHandler TextChanged = delegate { };

        public string Text
        {
            get { return text ?? (text = DateTime.Now.ToString()); }

            set
            {
                text = value;
                TextChanged(this, EventArgs.Empty);
            }
        }
    }
</pre>
<p>In this example, a Presenter provides constructors for being instantiated with default or provided instances of the View and Model. The Presenter sets its private View and Model instances, sets the View’s Presenter property to itself, and then registers to receive event notifications when the Model changes. When notified, the Presenter updates the Text property of the View.</p>
<p>As with the previous example, the View contains a Button_Click() event handler representing the initial interceptor for a button control. When invoked, it delegates control to the Presenter.OnButtonClick() method.</p>
<p>The following is a test for the presentation logic contained within the Presenter:</p>
<pre class="brush: csharp;">
    [TestClass]
    public class ViewTest
    {
        [TestMethod]
        public void PresenterShouldUpdateViewOnModelChange()
        {
            var model = new Model {Text = &quot;Initial value&quot;};
            var view = new StubView();
            var presenter = new Presenter(view, model);
            model.Text = &quot;Changed value&quot;;
            Assert.AreEqual(view.Text, &quot;Changed value&quot;);
        }
    }

    class StubView : IView
    {
        public IPresenter Presenter { get; set; }
        public string Text { get; set; }

        public void Show()
        {
        }
    }
</pre>
<p>The following code snippet demonstrates how the View might be displayed using the Encapsulated View style:</p>
<pre class="brush: csharp;">
    public class Program
    {
        public static void Main(string[] args)
        {
            // Show the view
            var presenter = new Presenter();
            presenter.ShowView();

            // Retrieve the view state
            string text = presenter.Text;
            Console.WriteLine(&quot;View text: &quot; + text);
            Console.ReadKey(true);
        }
    }
</pre>
<p>While this approach eliminates the need to expose delegating methods on the View (often necessary with the Encapsulated Presenter style), it can result in an inverse need to provide wrapper methods on the Presenter for accessing view state. This can be observed in the above example with the Presenter’s Text property. Another approach taken is to provide direct access to the View as a public property of the Presenter. This, however, constitutes a Law of Demeter violation and as such is considered by some to be a poor programming practice.</p>
<h2>The Observing Presenter Style</h2>
<p>The final style considered here will be referred to as the Observing Presenter style. Following this style, the Presenter is notified of pertinent activity within the View via the Observer Pattern. The View defines events or delegates to be raised in response to user interaction (or exposes event-raising components), while the Presenter registers for the appropriate events for handling the desired presentation logic.</p>
<p><a href="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/ObservingPresenter.png"><img class="aligncenter size-full wp-image-72" title="ObservingPresenter" src="http://www.aspiringcraftsman.com/wordpress/wp-content/uploads/2008/11/ObservingPresenter.png" alt="" width="372" height="688" /></a></p>
<p>This style may be used alongside both the Encapsulated Presenter or Encapsulated View styles. When following the Encapsulated Presenter style, the end user and external components interact directly with the View which raises events handled by the Presenter. When following the Encapsulated View style, user interaction with the View raises events handled by the Presenter, while other components interact directly with the Presenter.</p>
<p>The benefit of the Observing Presenter style is that it completely decouples knowledge of the Presenter from the View making the View less susceptible to changes within the Presenter.</p>
<p>The following example demonstrates the Observing Presenter style with the View encapsulated by the Presenter:</p>
<pre class="brush: csharp;">
    public interface IView
    {
        string Text { get; set; }
        event EventHandler ButtonClick;
        void Show();
    }

    public class View : IView
    {
        public View()
        {
        }

        public event EventHandler ButtonClick;
        public string Text { get; set; }

        public void Show()
        {
            Console.WriteLine(&quot;Current Time: &quot; + Text);
        }
    }

    public interface IPresenter
    {
        string Text { get; set; }
        void ShowView();
    }

    public partial class Presenter : IPresenter
    {
        IModel model;
        IView view;

        public Presenter() : this(new View(), new Model())
        {
        }

        public Presenter(IView view) : this(view, new Model())
        {
        }

        public Presenter(IView view, IModel model)
        {
            this.view = view;
            this.model = model;
            InitializeEvents();
        }

        public string Text
        {
            get { return view.Text; }
            set { view.Text = value; }
        }

        public void ShowView()
        {
            // Update view when shown
            view.Text = model.Text;
            view.Show();
        }

        void InitializeEvents()
        {
            model.TextChanged += new EventHandler(model_TextChanged);
            view.ButtonClick += new EventHandler(view_ButtonClick);
        }

        void view_ButtonClick(object sender, EventArgs e)
        {
            OnButtonClick();
        }

        void model_TextChanged(object sender, EventArgs e)
        {
            view.Text = model.Text;
        }

        protected virtual void OnButtonClick()
        {
            model.Text = &quot;Button Clicked&quot;;
        }
    }

    public interface IModel
    {
        string Text { get; set; }
        event EventHandler TextChanged;
    }

    public class Model : IModel
    {
        string text;
        public event EventHandler TextChanged = delegate { };

        public string Text
        {
            get { return text ?? (text = DateTime.Now.ToString()); }

            set
            {
                text = value;

                TextChanged(this, EventArgs.Empty);
            }
        }
    }
</pre>
<p>As with the first Encapsulated View example, this example contains a Presenter which provides constructors for being instantiated with default or provided instances of the View and Model. The Presenter sets its private View and Model instances, but this time registers to receive event notifications from both the Model and the View. When notified of changes within the Model, the Presenter updates the Text property of the View. When notified of user interaction on the View, the Model is updated.</p>
<p>The following is a test for the presentation logic contained within the Presenter:</p>
<pre class="brush: csharp;">
    [TestClass]
    public class ViewTest
    {
        [TestMethod]
        public void PresenterShouldUpdateViewOnModelChange()
        {
            var model = new Model {Text = &quot;Initial value&quot;};
            var view = new StubView();
            var presenter = new Presenter(view, model);
            model.Text = &quot;Changed value&quot;;
            Assert.AreEqual(view.Text, &quot;Changed value&quot;);
        }
    }

    class StubView : IView
    {
        public string Text { get; set; }
        public event EventHandler ButtonClick = delegate { };

        public void Show()
        {
        }

        public void OnButtonClick()
        {
            ButtonClick(this, EventArgs.Empty);
        }
    }
</pre>
<p>The same code demonstrating how the View might be displayed using the Encapsulated View style applies equally for this example:</p>
<pre class="brush: csharp;">
  public class Program

  {

   public static void Main(string[] args)

      {

   // Show the view

          IPresenter presenter = new Presenter();

          presenter.ShowView();

   // Retrieve the view state

   string text = presenter.Text;

          Console.WriteLine(&quot;View text: &quot; + text);

          Console.ReadKey(true);

      }

  }
</pre>
<p>While use of the Observer Pattern further decouples the Presenter from the View, this can introduce some added complexity, particularly with respect to testing the behavior contained within the Presenter. Since event handlers are generally marked either private or protected, they are not readily accessible within a unit test. In general, testing the internals of a component is unnecessary since all behavior is normally exercised through the component’s public interface. Unfortunately, this is often not the case with delegates. A thorough discussion of testing non-public methods and event handlers is beyond the intended scope of this article. However, one approach that can be used for this type of testing is to provision delegate invocation through a testing stub.</p>
<p>In the following example, a Presenter contains an event handler which expects a custom EventArgs generic type containing a Data property of type string:</p>
<pre class="brush: csharp;">
    public class Presenter : IPresenter
    {
        // ...

        void view_ButtonClick(object sender, DataEventArgs&lt;string&gt; e)
        {
            OnButtonClick(e.Data);
        }

        protected virtual void OnButtonClick(string value)
        {
            model.Text = value;
        }

        // ...
    }
</pre>
<p>By supplying a testing stub with a method for raising the event with an expected value, the resulting state can be tested without direct access to the Presenter method:</p>
<pre class="brush: csharp;">
    [TestClass]
    public class ViewTest
    {
        [TestMethod]
        public void OnButtonClickSetsExpectedValue()
        {
            var view = new StubView();
            var presenter = new Presenter(view);
            view.OnButtonClick(&quot;Expected Value&quot;);
            Assert.AreEqual(view.Text, &quot;Expected Value&quot;);
        }
    }

    public class StubView : IView
    {
        public string Text { get; set; }

        public void Show()
        {
        }

        public event EventHandler&lt;string&gt; ButtonClick = delegate { };

        public void OnButtonClick(string value)
        {
            ButtonClick(this, new DataEventArgs&lt;string&gt;(value));
        }
    }
</pre>
<h2>Conclusion</h2>
<p>While there are several approaches to how one may implement the Model-View-Presenter pattern, the chosen approach is to some degree a matter of personal taste. That being said, each approach does have its pros and cons. When choosing one style over another, consider the impact the chosen approach will have on the style and level of testing to be performed along with the encapsulation requirements of the application.</p>
<img src="http://feeds.feedburner.com/~r/AspiringCraftsman/~4/7BIDrYqKR_k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.aspiringcraftsman.com/2008/11/model-view-presenter-styles/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.aspiringcraftsman.com/2008/11/model-view-presenter-styles/</feedburner:origLink></item>
	</channel>
</rss>
