<?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:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>VusCode - Coding dreams since 1998!</title><link>http://blog.vuscode.com/malovicn/default.aspx</link><description>.NET exploration, articles, cool links, surf logs, book reviews, .net, c#, smart clients, software factories, patterns &amp;amp; practices, web casts and much more</description><dc:language>en</dc:language><generator>CommunityServer 2007 (Build: 20416.853)</generator><geo:lat>50.05</geo:lat><geo:long>14.25</geo:long><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/vuscode" type="application/rss+xml" /><feedburner:emailServiceId>vuscode</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item><title>Fluent NHibernate samples – Auto mapping (Part 1/2)</title><link>http://feedproxy.google.com/~r/vuscode/~3/D5ynMQwjOFQ/fluent-nhibernate-samples-auto-mapping-part-1-2.aspx</link><pubDate>Wed, 04 Nov 2009 16:01:12 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1247</guid><dc:creator>malovicn</dc:creator><slash:comments>4</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1247</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/11/04/fluent-nhibernate-samples-auto-mapping-part-1-2.aspx#comments</comments><description>&lt;p&gt;In my &lt;a href="http://blog.vuscode.com/malovicn/archive/2009/11/03/fluent-nhibernate-samples-on-codeplex.aspx"&gt;previous blog post&lt;/a&gt;, I have announced the sample solution with which I try to provide code sample for very comprehensive documentation which can be found on &lt;a title="http://fluentnhibernate.org/" href="http://fluentnhibernate.org/"&gt;http://fluentnhibernate.org/&lt;/a&gt;..&lt;/p&gt;  &lt;p&gt;The project is hosted on CodePlex (&lt;a title="http://fnhsamples.codeplex.com/" href="http://fnhsamples.codeplex.com/"&gt;http://fnhsamples.codeplex.com/&lt;/a&gt;). Right now it contains just a small sample which I would use in this blog post but in the future I intend to grow it until I wouldn’t cover most of the interesting features FNH offers.&lt;/p&gt;  &lt;p&gt;The purpose of project is just to demo how fluent nhibernate mappings work so you can quickly “get them” and NOT:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;to teach on how NHibernate works (buy &lt;a href="http://www.amazon.com/NHibernate-Action-Pierre-Henri-Kuat%C3%A9/dp/1932394923"&gt;this book&lt;/a&gt; for that) &lt;/li&gt;    &lt;li&gt;to teach you in detail about fluent nhibernate (go to &lt;a href="http://www.fluentnhibernate.org"&gt;http://www.fluentnhibernate.org&lt;/a&gt; for that) &lt;/li&gt;    &lt;li&gt;to teach about best practices in abstracting NHibernate dependencies (you can find that &lt;a href="http://tinyurl.com/yfgmxff"&gt;here&lt;/a&gt;) &lt;/li&gt;    &lt;li&gt;to teach about best practices in domain modeling etc &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I am also by no means an expert in neither nhibernate nor fluent nhibernate. In fact I am just a grunt like many of you reading this blog post who was searching for similar blog post when he was banging his head against the wall trying to learn how to use it - 1+ year ago very little docs) so take EVERYTHING I say with a grain of salt.&lt;/p&gt;  &lt;p&gt;I am also aware of the state of my English, but I am really doing my best and if anyone wants to help editing the blog post I would put that version in code plex :)&lt;/p&gt;  &lt;p&gt;So, let’s start…&lt;/p&gt;  &lt;h1&gt;An example of Fluent NHibernate auto mapping in action&lt;/h1&gt;  &lt;p&gt;So, here’s the domain model I’ll be using in this blog post to show couple of FNH auto mapping aspects&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_49BE7E96.png" target="_blank"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_383DF7F1.png" width="804" height="297" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;And here’s the database model which would be created after the sample would be executed based on fluent nhibernate auto mapping conventions.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_66E8324C.png"&gt;&lt;img title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_25014CFE.png" width="804" height="467" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;(To get more details about the domain design check the use case description from &lt;a href="http://blog.vuscode.com/malovicn/archive/2009/11/03/fluent-nhibernate-samples-on-codeplex.aspx"&gt;previous blog post&lt;/a&gt;)&lt;/p&gt;  &lt;h2&gt;Convention over the configuration&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_7A80EA67.png"&gt;&lt;img style="border-right-width:0px;margin:0px 20px 0px 0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" align="left" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_721D1510.png" width="127" height="244" /&gt;&lt;/a&gt;FNH auto mapping works based on applying the convention over the configuration which I usually try to explain like this…&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;“There is a set of rules which would be applied to your domain during its mapping to database model. &lt;/p&gt;    &lt;p&gt;Here are couple of examples of rules\conventions: &lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;Database table would be named used plural form of the entity name. &lt;/li&gt;      &lt;li&gt;Primary key of every table would be named following the rule “entity name” + “ID” &lt;/li&gt;   &lt;/ul&gt;    &lt;p&gt;Fluent NHibernate comes with a default set of rules which you can customize to your own preferences on a very cool and easy way.&lt;/p&gt; &lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;Sounds simple? It is THAT simple.”&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Let&amp;#39; see quickly how the fluent nhibernate magic happens.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h3&gt;How the Fluent NHibernate Auto mapping magic works (explanation for us others)?&lt;/h3&gt;  &lt;p&gt;I won’t go deep into the details (for that go to &lt;a href="http://fluentnhibernate.org"&gt;http://fluentnhibernate.org&lt;/a&gt; or &lt;a href="http://tinyurl.com/yjffhtk" target="_blank"&gt;How FNH works?&lt;/a&gt;) but in general it is based on two design patterns: &lt;a href="http://en.wikipedia.org/wiki/Proxy_pattern"&gt;Proxy&lt;/a&gt; and &lt;a title="http://en.wikipedia.org/wiki/Visitor_pattern" href="http://en.wikipedia.org/wiki/Visitor_pattern"&gt;Visitor&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;If you are not familiar with the patterns here’s a simple way for you to get them in the context of fluent nhibernate magic.&lt;/p&gt;  &lt;h4&gt;The role of proxy design pattern in fluent nhibernate&lt;/h4&gt;  &lt;p&gt;If you check out some of the entities in Vuscode.FNHSamples.Domain project you would see that all of them are non sealed classes with all of the members being virtual…&amp;#160; So, the code like this&lt;/p&gt;  &lt;pre class="c-sharp"&gt;namespace Vuscode.FNHSamples.Domain
{
    public class Address
    {
        public virtual string Email { get; set; }

        public virtual string City { get; set; }
        
        public virtual string Country { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;The reason why we HAVE TO respect this rules designing our domain classes is related to the fact that FNH uses castle dynamic proxy functionalities to (in overly simplified version) create an “in memory” proxy child class by inheriting the real one and overriding the properties in the proxy child class in order to enable intercepting their calls.&lt;/p&gt;

&lt;p&gt;In this example therefore inside of the FNH engine there would be created a “ProxyAddress” class inheriting from the Address class but which would have implemented additional interfaces and override members effectively adding during the run time behaviors and shapes to original Address class. That’s how a POCO can be achieved: we don’t need any attributes, no special base class or base interface etc..&lt;/p&gt;

&lt;p&gt;Now, in order to understand why FNH needs this we need to take a quick peek at how FNH “mapping rules” (properly called &lt;strong&gt;conventions&lt;/strong&gt;) are implemented.&lt;/p&gt;

&lt;h4&gt;&lt;/h4&gt;

&lt;h4&gt;How the fluent nhibernate conventions are implemented?&lt;/h4&gt;

&lt;p&gt;Always on the same way (thanks to brilliant work of FNH authors): always inherit and implement a special interface which has a method accepting a parameter of certain interface type.&lt;/p&gt;

&lt;pre class="c-sharp"&gt;    public class ClassConvention : IClassConvention 
    {
        public void Apply(IClassInstance instance)
        {
            // do something with instance
        }
    }&lt;/pre&gt;

&lt;p&gt;The reason why&amp;#160; our convention has to implement certain interface is due to the fact that during the run time fluent nhibernate would iterate over all of the types of the given assembly and collect “all of the types implementing the IClassConvention” thus “collecting the rules”. &lt;/p&gt;

&lt;p&gt;The reason why a IClassInstance parameter was passed is that the Apply method would get SOMETHING implementing that interface without knowing\caring about what that something really is.&lt;/p&gt;

&lt;p&gt;This design approach where you enable your class to work with various entities without coupling to its concrete implementation can be roughly called &lt;strong&gt;visitor pattern.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If I use gain the same sample of Address and “AddressProxy” class, imagine that AddressProxyClass created on the fly implements the IClassInstance interface. Wouldn’t that enable us to pass an instance of addressProxy class to ClassConvention Apply method so it could perform its functionality on it? :)&lt;/p&gt;

&lt;p&gt;The end result of those two patterns is that instance Address class ends inside of the Convention Apply method without adding anything to domain other then virtual keywords on properties. &lt;/p&gt;

&lt;h4&gt;Iterating, iterating, iterating…&lt;/h4&gt;

&lt;p&gt;During the runtime mapping process FNH (overly simplified) iterates over all of the types and creates their proxies. 
  &lt;br /&gt;Every proxy gets added certain interfaces which define methods allowing “outer world” to alter the state of proxy.&amp;#160; &lt;br /&gt;Fluent NHibernate (or user) then creates a collection of conventions defining the rules how certain aspects of proxies should be altered.&lt;/p&gt;

&lt;p&gt;Now the code iterates every proxy and for every proxy it iterates over all of the conventions and applies the one matching the proxy.&lt;/p&gt;

&lt;p&gt;As the end result of that iteration, we gat all of the proxies with their state sets up in proper state.&lt;/p&gt;

&lt;p&gt;Then FNH iterates all of the proxies again and translates states of each one of them to NHibernate required XML representation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Brilliant, isn’t it? &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;Back to reality &lt;/h2&gt;

&lt;p&gt;Now when I (hopefully) explained how NHibernate works in layman’s terms, we can just go over the conventions I have in my sample and provide explanation what is the relationship between them with certain pieces of my sample.&lt;/p&gt;

&lt;h3&gt;Class Convention&lt;/h3&gt;

&lt;p&gt;This is convention which tells to Fluent NHibernate how to map entities to database tables. &lt;/p&gt;

&lt;p&gt;I have only one rule related to that:”A table name should be plural form of the entity name”, so the code doing that is pretty simple&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.Framework.NHibernate.Conventions
{
    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.Instances;

    public class ClassConvention : IClassConvention 
    {
        public void Apply(IClassInstance instance)
        {
            instance.Table(Inflector.Pluralize(instance.EntityType.Name));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;IClassInstance has two key members (key in sense of this sample): &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;EntityType – providing access to a type being mapped to database table &lt;/li&gt;

  &lt;li&gt;Table(name) – method which sets the value of the table name. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(To explore capabilities outside of my sample use intellisense which in case of fluent interfaces is your best friend)&lt;/p&gt;

&lt;p&gt;Inflector is just a helper class I took from Castle.ActiveRecord project (been a long time ago) and which purpose is to get plural form of a given string. I put it also in sample project so you can check it out if you wish.&lt;/p&gt;

&lt;p&gt;So, now when we know all of the pieces we can read the implementation inside of Apply method like this&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;“Make sure that whatever the proxy was sent it would be mapped in a data table which name would be plural form of the original class proxy was created from”&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;(Due to the fact every convention is implemented in same manner implement a interface and get something injected I’ll skip repeating that in other conventions)&lt;/p&gt;

&lt;h3&gt;
  &lt;br /&gt;DefaultStringPropertyConvention&lt;/h3&gt;

&lt;p&gt;This is convention which tells how class string properties should be mapped in database column. &lt;/p&gt;

&lt;p&gt;My rules are simple: default length 100 and every string can be null value.&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.Framework.NHibernate.Conventions
{
    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.Instances;

    public class DefaultStringPropertyConvention : IPropertyConvention
    {
        public void Apply(IPropertyInstance instance)
        {
            instance.Length(100);
            instance.Nullable();
        }
    }
}&lt;/pre&gt;

&lt;h3&gt;Foreign Key Convention&lt;/h3&gt;

&lt;p&gt;This is convention which defines how fluent nhibernate should behave while mapping association properties to foreign keys.&lt;/p&gt;

&lt;p&gt;My rule is simple:”Name of the foreign key is name of the table being referenced + ID suffix” &lt;/p&gt;

&lt;p&gt;Here’s the code from sample&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System;

using FluentNHibernate.Conventions;
using System.Reflection;

namespace Vuscode.Framework.NHibernate.Conventions
{
    public class CustomForeignKeyConvention : ForeignKeyConvention
    {
        protected override string GetKeyName(PropertyInfo property, Type type)
        {
            return property == null 
                    ? type.Name + &amp;quot;ID&amp;quot; 
                    : property.Name + &amp;quot;ID&amp;quot;;
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see from the code not exact translation of my rule so it needs some additional clarification…&lt;/p&gt;

&lt;p&gt;The GetKeyName method accepts two parameters:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;property (holding a pointer to a property in entity referencing the “parent” entity &lt;/li&gt;

  &lt;li&gt;type (holding a pointer to a&amp;#160; “parent” table) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we check out the resulting DB diagram&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_4A0A65F1.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_7B95D386.png" width="525" height="185" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;and how the domain implementation of Blogs looks like&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System.Collections.Generic;

namespace Vuscode.FNHSamples.Domain
{
    public class Blog : Entity
    {
        public virtual Author Author { get; set;} // component

        public virtual BlogRoll Roll { get; set; } // references
        
        public virtual IList Posts { get; set; } // has many

        public virtual string BlogTitle { get; set; }

    }
}&lt;/pre&gt;

&lt;p&gt;We can clearly see that due to the fact that Blog has a Roll property pointing to parent BlogRoll, FNH took that property value + &amp;quot;ID&amp;quot; and created RollID foreign key in Blogs data table. So, that explains how FNH works in FK convention when property being sent is with non null value and leaves us with the question “how come that value can be null”?&lt;/p&gt;

&lt;p&gt;To answer that, let we check out the other part of the resulting UML diagram representing DB interpretation of the Author class inheritance &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_36E93945.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_2E8563EE.png" width="674" height="376" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;As you can see, GuestAuthor and RegularAuthor have their foreign keys named “AuthorID” even none of those two has an explicit “parent” property like in previous case. &lt;/p&gt;

&lt;p&gt;In other words There is no GuestAuthor.Author and RegularAuthor.Author properties but we still have the need for defining FK in their tables. &lt;/p&gt;

&lt;p&gt;In this type of cases, ForeignKeyConvention would get a null propertyInfo value (because there is no property) and a pointer to a entity to be used with defining of database FK (in this example Author). That’s how in my sample foreign key of those tables become &lt;/p&gt;

&lt;h4&gt;Many to Many convention &lt;/h4&gt;

&lt;p&gt;This is convention which defines how fluent nhibernate should behave while mapping the N – N relationships where a class A has a collection property of class B type and the class B has a collection property of class A.&lt;/p&gt;

&lt;p&gt;Here’s the code sample from the Vuscode.FNHSamples.Domain –&amp;gt; Post and Category classes&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.FNHSamples.Domain
{
    using System.Collections.Generic;

    public class Post : Entity
    {
        public virtual IList Categories { get; set; }  // has many to many

        public virtual string Title { get; set; }

        public virtual PostStatus Status { get; set; }

    }
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;A Post can have many Categories&lt;/em&gt;&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.FNHSamples.Domain
{
    using System.Collections.Generic;

    public class Category : Entity
    {
        public virtual IList Posts { get; set; } // has many to many

        public virtual string Name { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;One Category can be used in many samples.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I prefer mapping Many to many relationships using the &lt;a title="http://www.martinfowler.com/eaaCatalog/associationTableMapping.html" href="http://www.martinfowler.com/eaaCatalog/associationTableMapping.html"&gt;Association Table Mapping pattern&lt;/a&gt; where additional table is created with two foreign keys columns matching the primary keys of the associated tables.&lt;/p&gt;

&lt;p&gt;Here’s how it looks in resulting database model with PostsToCategories table being association table.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_4DC80AC1.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5F386B99.png" width="502" height="403" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I guess after seeing the diagram it is quite obvious to get the many to many convention I have: &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Name of the association class should be like “TableNameA” + “To” + “TableNameB”.&lt;/em&gt;&lt;/p&gt;

&lt;h5&gt;&lt;/h5&gt;

&lt;h5&gt;How NOT to implement many to many relationship&lt;/h5&gt;

&lt;p&gt;As you can read in great detail &lt;a href="http://wiki.fluentnhibernate.org/Getting_started"&gt;here&lt;/a&gt;, many to many is in general combination of two 1 – N relationships which if it would be done like this&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.Framework.NHibernate.Conventions
{
    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.Instances;

    public class ManyToManyConvention : IHasManyToManyConvention
    {
        public void Apply(IManyToManyCollectionInstance instance)
        {
            instance.Table(
            	string.Format(&amp;quot;{0}To{1}&amp;quot;,
                        Inflector.Pluralize(instance.EntityType.Name),
                        Inflector.Pluralize(instance.ChildType.Name))
		);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Would result in next database diagram state&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_3387A19D.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_76173D15.png" width="673" height="473" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;So, we have 2 associations tables where each one of them covers their own path. &lt;/p&gt;

&lt;p&gt;Clearly this is an overkill from Db perspective due to the fact that the same table can be used in both paths. &lt;/p&gt;

&lt;p&gt;In NHibernate parlance that is achieved using Inverse relation type (again, you can read about it in great detail &lt;a href="http://wiki.fluentnhibernate.org/Getting_started"&gt;here&lt;/a&gt;) which in layman’s terms can be explained “when you need to map the Post –&amp;gt; Categories relation, pleas use the already defined Categories –&amp;gt; Post and just revert it”&lt;/p&gt;

&lt;p&gt;And that’s exactly what the actual implementation in my code sample does&lt;/p&gt;

&lt;p&gt;Here’s the code&lt;/p&gt;

&lt;p&gt;Let see how this was implemented in the sample code&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace Vuscode.Framework.NHibernate.Conventions
{
    using FluentNHibernate.Conventions;
    using FluentNHibernate.Conventions.Instances;

    public class ManyToManyConvention : IHasManyToManyConvention
    {
        public void Apply(IManyToManyCollectionInstance instance)
        {
            if (instance.OtherSide == null)
            {
                instance.Table(
                    string.Format(
                        &amp;quot;{0}To{1}&amp;quot;,
                        Inflector.Pluralize(instance.EntityType.Name),
                        Inflector.Pluralize(instance.ChildType.Name)));
            }
            else
            {
                instance.Inverse();
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;The instance.OtherSide is null in situation when there is no already defined relationship between EntityType and ChildType. In that case code uses Table method to set the name of association table respecting my naming convention TableA name + “To” + TableB name. That first if would result with PostsToCategories association table being created.&lt;/p&gt;

&lt;p&gt;Now the FNH would iterate more (as described above) and the Post –&amp;gt; Category relation would be processed. When this happens, instance.OtherSide would NOT be null so instead of creating new association table FNH would map that relation as inverse to the original one.&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;This blog post become really long so I have decided to split it in two posts. In next post I’ll show a few more conventions and process of fluent configuration with switches I’ve been using in my sample &lt;/p&gt;

&lt;p&gt;Stay tuned :)&lt;/p&gt;

&lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:cff38b11-5e43-4e81-af0f-66dee528e405" class="wlWriterEditableSmartContent"&gt;del.icio.us Tags: &lt;a href="http://del.icio.us/popular/fluent+nhibernate" rel="tag"&gt;fluent nhibernate&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/auto+mapping" rel="tag"&gt;auto mapping&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/fnh" rel="tag"&gt;fnh&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1247" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=D5ynMQwjOFQ:dkfyABl9Sx0:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=D5ynMQwjOFQ:dkfyABl9Sx0:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=D5ynMQwjOFQ:dkfyABl9Sx0:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=D5ynMQwjOFQ:dkfyABl9Sx0:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/D5ynMQwjOFQ" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/11/04/fluent-nhibernate-samples-auto-mapping-part-1-2.aspx</feedburner:origLink></item><item><title>Fluent NHibernate Samples on CodePlex</title><link>http://feedproxy.google.com/~r/vuscode/~3/j4kM9IkiuEk/fluent-nhibernate-samples-on-codeplex.aspx</link><pubDate>Tue, 03 Nov 2009 19:37:29 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1243</guid><dc:creator>malovicn</dc:creator><slash:comments>2</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1243</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/11/03/fluent-nhibernate-samples-on-codeplex.aspx#comments</comments><description>&lt;p&gt;I’ve been using Fluent NHibernate for more then a year now and I am big fan of it. &lt;/p&gt;  &lt;p&gt;The were only two things bothering me in FNH for all that 1+ year:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;frequent API changes (which made my &lt;a title="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" href="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx"&gt;fluent mapping&lt;/a&gt; and &lt;a title="http://blog.vuscode.com/malovicn/archive/2009/01/03/fluent-nhibernate-nhibernate-without-configuration-files-automap-magic.aspx" href="http://blog.vuscode.com/malovicn/archive/2009/01/03/fluent-nhibernate-nhibernate-without-configuration-files-automap-magic.aspx" target="_blank"&gt;auto mapping&lt;/a&gt; blog post pretty quick completely obsolete – not to mention my code :)), but when I saw how polished FNH get in 1.0 version I don’t mind any more – simply beautiful code.&lt;/li&gt;    &lt;li&gt;lack of documentation. Don’t get me wrong - &lt;a title="http://groups.google.com/group/fluent-nhibernate" href="http://groups.google.com/group/fluent-nhibernate"&gt;http://groups.google.com/group/fluent-nhibernate&lt;/a&gt; was REALLY useful most of the the time but I was allways dreaming about something like the current &lt;a href="http://wiki.fluentnhibernate.org/Main_Page"&gt;fluent nhibernate wiki&lt;/a&gt; which is simply awesome concentrated amount of useful data.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So, to me there’s no more problems with FNH left (beside a few minor bugs &lt;a href="http://stackoverflow.com/questions/1571779/fluentnhibernate-setting-default-value-for-db-columns-sql-server"&gt;no one cares to answer\fix&lt;/a&gt;) but in last couple of days I’ve accidentally find out ( &lt;a href="http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/5bf16d37dc56bf20?hl=en"&gt;here on the fnh mailing list&lt;/a&gt; and &lt;a href="http://stackoverflow.com/questions/1644186/is-there-a-fluent-nhibernate-automapping-sample-project-that-just-works"&gt;here on stackoverflow&lt;/a&gt;) that a lot of folks would like to see a sample code working with fluent nhibernate 1.0 (beside the wiki etc)&lt;/p&gt;  &lt;p&gt;That’s why I decided to loop in some of my time today and create a sample project illustrating on a same example both fluent and auto mapping and that’s how I came with &lt;/p&gt;  &lt;h1&gt;CodePlex project - Fluent Nhibernate samples&lt;/h1&gt;  &lt;p&gt;The intention of the project is to initially focus on single sample illustrating all of the major use cases in the ‘real world’ manner and then to slowly grow so the sample would start covering more and more corner cases. Hopefully in a long term it would become a c# solution illustrating in one place all of the major FNH usage aspects.&lt;/p&gt;  &lt;p&gt;Project can be found on this location &lt;a title="http://fnhsamples.codeplex.com/" href="http://fnhsamples.codeplex.com/"&gt;http://fnhsamples.codeplex.com/&lt;/a&gt; together with the source code downloadable as zip or SVN-checkout.&lt;/p&gt;  &lt;h3&gt;&lt;/h3&gt;  &lt;h2&gt;Starting solution&lt;/h2&gt;  &lt;p&gt;So, in order to start the project and based on the questions I am usually hearing mentioned regarding auto mapping I’ve came up&amp;#160; with this simple domain model&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_4F87C424.png" target="_blank"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_32BE2942.png" width="802" height="297" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;p&gt;So a domain space covers imaginary blog engine where:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;a blog roll is a group of blogs (e.g. codebetter.com), &lt;/li&gt;    &lt;li&gt;a blog contain one or many blog posts where every blog post can have one or many categories&lt;/li&gt;    &lt;li&gt;a blog is owned by a single author which can be regular author (that blog is his primary blog) or guest (where he cross post to this blog)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;As you can see in this very simple domain I have cases of:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;strong&gt;References &lt;/strong&gt;(N – 1 relation) where many Blogs belong to one BlogRoll (in this sample Blog mimics aggregate root) &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;HasOne&lt;/strong&gt;&amp;#160; (1 – 1 relation)&amp;#160; where author can have only one blog in a blog role and all blog posts of a blog are written by a single author only.&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Component &lt;/strong&gt;where author has a complex Address value property of a Address type which (due to the fact it is not entity) we would like to map to same DB table as Author.&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Subclass (&lt;/strong&gt;inheritance&lt;strong&gt;)&lt;/strong&gt;where GuestAuthor and RegularAuthor are children of the abstract Author with each one of them having its own custom properties&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;HasMany &lt;/strong&gt;(1 – N relation) where a blog has one or many blog posts&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;ManyToMany &lt;/strong&gt;(N – N relation)&amp;#160; where a post can be tagged with many categories and every category can be used in many posts&lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Enumeration&amp;#160; - &lt;/strong&gt;where a post has status enumerated value column&lt;/li&gt;    &lt;li&gt;All entities share the same Entity base class which (contrary to Author entity) is not supposed to be mapped in a separate table&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Note: I know that this domain model is far from perfect in modeling sense but that is not the point here. The point here is having a meaningful sample which would be used to showcase all the fluent nhibernate magic.&lt;/p&gt;  &lt;h2&gt;End result&lt;/h2&gt;  &lt;p&gt;Here’s how the DB model would look like created using both fluent and auto mappings &lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_6DE1DF40.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_331A366A.png" width="802" height="465" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://fnhsamples.codeplex.com/"&gt;&lt;/a&gt;&lt;a href="http://fnhsamples.codeplex.com/"&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;As you can see, DB diagram match pretty much the domain model and all that (in case of Auto Mapping) just by utilizing conventions without any manual defined mappings.&lt;/p&gt;  &lt;h2&gt;What next?&lt;/h2&gt;  &lt;p&gt;For the folks curious to check it out now, go to &lt;a title="http://fnhsamples.codeplex.com/" href="http://fnhsamples.codeplex.com/"&gt;http://fnhsamples.codeplex.com/&lt;/a&gt;&amp;#160; where you can download the source currently containing only auto mapping based solution. I guess, it is so simple that most of us could get it just by looking at the small code base there.&lt;/p&gt;  &lt;p&gt;For the rest of the people, my next blog post would present the fluent mapping based solution to get from model to DB diagram and after that auto mapping based solution. In that two blog posts, I would comment “line-by-line” so even people new to fluent nhibernate would (I hope) get it.&lt;/p&gt;  &lt;p&gt;After that two blog posts, I would have to switch gears and (finally) spit out couple of things I came out with doing Prism development. &lt;/p&gt;  &lt;p&gt;I hope at that moment there would be some suggestions what needs to be added to the sample so the sample would start to grow from its starting trivial size.&lt;/p&gt;  &lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f9933831-cba7-47be-860c-35730bc35651" class="wlWriterEditableSmartContent"&gt;del.icio.us Tags: &lt;a href="http://del.icio.us/popular/fluent+nhibernate" rel="tag"&gt;fluent nhibernate&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/samples" rel="tag"&gt;samples&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/auto+mapping" rel="tag"&gt;auto mapping&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/fluent+mapping" rel="tag"&gt;fluent mapping&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/fnh" rel="tag"&gt;fnh&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/how-to" rel="tag"&gt;how-to&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1243" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=j4kM9IkiuEk:F1snQaKcj2g:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=j4kM9IkiuEk:F1snQaKcj2g:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=j4kM9IkiuEk:F1snQaKcj2g:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=j4kM9IkiuEk:F1snQaKcj2g:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/j4kM9IkiuEk" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/11/03/fluent-nhibernate-samples-on-codeplex.aspx</feedburner:origLink></item><item><title>Me, myself and design patterns</title><link>http://feedproxy.google.com/~r/vuscode/~3/dZ4vUjCZlqQ/me-myself-and-design-patterns.aspx</link><pubDate>Mon, 02 Nov 2009 00:02:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1232</guid><dc:creator>malovicn</dc:creator><slash:comments>5</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1232</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/11/02/me-myself-and-design-patterns.aspx#comments</comments><description>&lt;p&gt;Looks like the Silverlight related posts I’ve announced would have to wait one more blog post due to the event which happened to me today and which made me thinking about a few of the architecture related things which at the end resulted with a few of (at least for me) interesting thought I felt sharing with the community.&lt;/p&gt;  &lt;h1&gt;The event&lt;/h1&gt;  &lt;p&gt;So, a fellow blogger @RadenkoZec made a nice &lt;a href="http://blog.developers.ba/post/2009/10/31/Unit-testing-Facade-pattern.aspx" target="_blank"&gt;blog post about Facade design pattern&lt;/a&gt; in which comments we had a discussion if the example is appropriate or not, and if the implementation is Facade design pattern&amp;#160; or some other pattern. I won’t repeat here in detail what we were discussed there (go to the blog post to read comments) but there were couple of things in that discussion I was thinking about during the evening…&lt;/p&gt;  &lt;h1&gt;Patterns should be explored in 3D&lt;/h1&gt;  &lt;p&gt;It is very interesting that the sites on the net (like the &lt;a title="http://www.dofactory.com/patterns/" href="http://www.dofactory.com/patterns/"&gt;dotfactory.com&lt;/a&gt;) seems to be primarily focused on GoF patterns while I was not able to find sites covering at the same time PoEAA patterns and\or DDD patterns. &lt;/p&gt;  &lt;p&gt;That fact might look irrelevant but if you would check out the content of today’s discussion you would se that the same example code used in blog post &lt;/p&gt;  &lt;p&gt;looked to Radenko as &lt;a href="http://en.wikipedia.org/wiki/Facade_pattern"&gt;Facade&lt;/a&gt; (GoF)&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;a href="http://en.wikipedia.org/wiki/File:FacadeDesignPattern.png"&gt;&lt;img alt="FacadeDesignPattern.png" src="http://upload.wikimedia.org/wikipedia/en/a/ac/FacadeDesignPattern.png" width="511" height="388" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;and to me more like a &lt;a href="http://martinfowler.com/eaaCatalog/gateway.html"&gt;Gateway&lt;/a&gt; (PoEEA)&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/gatewaySketch_0B01DA85.gif"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="gatewaySketch" border="0" alt="gatewaySketch" src="http://blog.vuscode.com/blogs/blogs/malovicn/gatewaySketch_thumb_49F35B20.gif" width="488" height="218" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;If you just take a look at above pictures, you would find for sure at least some similarity and that’s why one should look at all of the patterns in whole and not just be exclusive in picking “The book”. Another example of this interpretation conflict can be found between the PoEAA and DDD where patterns such as repository, factory etc some times have different usages if not different meanings.&lt;/p&gt;  &lt;p&gt;In other words, IMHO every developer should persist knowledge in three dimensions: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;X– DDD, PoEAA, GoF &lt;/li&gt;    &lt;li&gt;Y – specific patterns and their implementations, implications; &lt;a href="http://en.wikipedia.org/wiki/Anti-pattern"&gt;anti patterns&lt;/a&gt; too. &lt;/li&gt;    &lt;li&gt;Z – time &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;For the ones of you probably asking what time has to do with this subject - here’s an answer. Software landscape changes significantly in last 20 years so some of the “scriptures” should be taken with a grain of salt. &lt;/p&gt;  &lt;p&gt;Here are couple of examples illustrating my point: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Observer pattern doesn’t have a lot of sense being implemented out of box with .NET events, &lt;/li&gt;    &lt;li&gt;Singletons (btw, would have a dedicated post showing how evil they are) are kind of obsolete with the usage of the IoC containers etc &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Another aspect of the need for considering the time dimension in design patterns exploration is the fact that in last few years we are all witnessing both the rise of the dynamic languages and the enhancement of static languages where they are getting aspects not existing in the time when “pattern Bibles” were made (lambdas, generics, C# 4.0 dynamic etc). Every of the patterns therefore should be heretically challenged in the lieu of current state of technology.&lt;/p&gt;  &lt;h1&gt;Context is the king&lt;/h1&gt;  &lt;p&gt;By mare looking at above diagrams (which for my point can be both pure UML diagrams) it would be really hard to tell what is the difference..&lt;/p&gt;  &lt;p&gt;In both cases we have multiple classes encapsulated in one class orchestrates their calls and expose simple API to be consumed. &lt;/p&gt;  &lt;p&gt;But if you take a look at the context you can see based on the provided code sample that the packages in case of facade are interconnected, each one of their classes is dependable in it’s own way dependable on other classes and none of them can exist without others. I could imagine refactoring merging those 3 classes in one. In other words, even physically we have multiple classes caring their own implementation they are so connected that on architectural level there’s just one entity which is hiding behind the facade. &lt;/p&gt;  &lt;p&gt;That’s why for me Facade &lt;strong&gt;feels like&lt;/strong&gt; “1 – 1” relationship type pattern where a facade &lt;strong&gt;hides&lt;/strong&gt; the complexity of the class (similar in a way to adapter but let’s not digress with that here)&lt;/p&gt;  &lt;p&gt;The second case is with clearly different context where all of the packages behind the “facade” (Gateway) are quite independent. They do not depend on each other at all, they cooperate as partners. &lt;/p&gt;  &lt;p&gt;The purpose of the PricingGateway is also to expose a simple API to pricing Package but this time when the API would be used Gateway would perform a role of a conductor, orchestrating the calls to the &amp;quot;hided&amp;quot; elements.&lt;/p&gt; &lt;a href="http://www.ted.com/talks/view/id/663" target="_blank"&gt;&lt;img src="http://images.ted.com/images/ted/tedindex/embed-posters/ItayTalgam-2009G.embed_thumbnail.jpg" alt="" /&gt;&lt;/a&gt;   &lt;p&gt;That’s why for me Gateway &lt;strong&gt;fells more&lt;/strong&gt; like a “1 – n” relationship type design pattern&lt;/p&gt;  &lt;p&gt;To summarize: In order to distinct patterns one would have to understand the problem\implementation context before picking the right flavor – appropriate pattern.&lt;/p&gt;  &lt;h1&gt;Patterns as a matter of feelings&lt;/h1&gt;  &lt;p&gt;As you have probably noticed in the text above I am using the “feels like to me” which I’m pretty sure is looking quite unrelated to explicit and scientific thing such are the design patterns so let me clarify that for you :)&lt;/p&gt;  &lt;p&gt;As many other, I’ve stepped through couple of phases in my Pattern life&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Discovery of patterns (we hear about them from some of the cool kids and all we do at this stage is trying to pretend as best as we can to look like we know what they are talking about) &lt;/li&gt;    &lt;li&gt;Trying to get it (AKA “I found\read the GoF book”) &lt;/li&gt;    &lt;li&gt;Becoming a believer (including &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/08/11/using-design-patterns-in-real-world-applications-altairis-kalend-225-akc-237.aspx"&gt;making the presentations&lt;/a&gt; to people in phase #1) &lt;/li&gt;    &lt;li&gt;Getting it for real (reading every patterns book, blog post etc you can find and memorizing the UML diagrams, use cases etc) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://en.wikipedia.org/wiki/Golden_hammer"&gt;Seeing patterns everywhere&lt;/a&gt;&amp;#160; and doing them as much as we can &lt;/li&gt;    &lt;li&gt;Paying the price from &lt;a href="http://www.phppatterns.com/docs/design/hello_world_in_patterns"&gt;highly complex code base&lt;/a&gt; . &lt;/li&gt;    &lt;li&gt;Starting to understand the price of patterns application and start using it only when a real design pain is identified which can not be solved on simpler (but still clean) solution &lt;/li&gt;    &lt;li&gt;Instead of patterns catalogs starting to focus on basic principles. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So, as far I can tell I am in that phase #8 where all of the patterns somehow melted with each other and all of them “look similar”. I forgot half of their UML diagrams and reference implementations. The only thing in my head left is the name of the pattern, notion of the use case when it is useful and (very blurry for most of them) how it works.&lt;/p&gt;  &lt;p&gt;Reading my last statement someone could make a conclusion that I just got more stupid (possible option I admit :)) and to lazy to remember things but I would disagree with him because every one of the patterns I faced is based on the same set of plain logic principles which in case you know and feel them you are good to go with doing “your own” solution which would somehow match some of the patterns. &lt;/p&gt;  &lt;p&gt;Here are some of examples of the design principles I have on my mind: SOLID, open-close, DRY, KISS, &lt;a title="http://codebetter.com/blogs/jeremy.miller/archive/2007/01/08/Orthogonal-Code.aspx" href="http://codebetter.com/blogs/jeremy.miller/archive/2007/01/08/Orthogonal-Code.aspx" target="_blank"&gt;orthogonal code&lt;/a&gt;,&amp;#160; OOP principles (encapsulation, abstraction), TDD, dependency injection and the list could go on with pages&lt;/p&gt;  &lt;p&gt;To summarize: I strongly believe that if the developer is feeling natural regarding the design principles (spits out the code following those principles without even thinking) the knowledge of the design pattern can be at much more abstract level (in a way like knowing a page index of a book) without memorizing every bit of their reference implementation (that’s why we have &lt;a href="http://www.bing.com" target="_blank"&gt;bing&lt;/a&gt; aren’t we?) and the created code would still comply to all of those patterns.&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Conclusion&lt;/h1&gt;  &lt;p&gt;I hope all of my rumblings I shared with you my dear reader would help me now to make up the point of this blog post and that is to explain how come when Radenko pulled (completely rightfully) on his blog post couple of referent examples from sites and books of folks far smarter then I am proving that his example implementation is the same as the one they provided, the only thing I could tell him is that his example &lt;em&gt;“&lt;strong&gt;doesn’t feel &lt;/strong&gt;like a case for Facade to me”.&amp;#160; &lt;/em&gt;&lt;/p&gt;  &lt;p&gt;I was not claiming neither that the guy who wrote a book did it wrong nor that the dotfactory.com site got it wrong in their sample. &lt;/p&gt;  &lt;p&gt;It was just a gut filling of a pragmatic “duct tape architect” which I would have about that code if it would be mine which I shared with him and the community.&lt;/p&gt;  &lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:f9b68883-4a4f-47f2-a0c1-00d0dae15c6a" class="wlWriterEditableSmartContent"&gt;del.icio.us Tags: &lt;a href="http://del.icio.us/popular/design+patterns" rel="tag"&gt;design patterns&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/architecture" rel="tag"&gt;architecture&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/facade" rel="tag"&gt;facade&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/gateway" rel="tag"&gt;gateway&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/PoEAA" rel="tag"&gt;PoEAA&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/GoF" rel="tag"&gt;GoF&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1232" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=dZ4vUjCZlqQ:t-p4r4MIhKk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=dZ4vUjCZlqQ:t-p4r4MIhKk:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=dZ4vUjCZlqQ:t-p4r4MIhKk:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=dZ4vUjCZlqQ:t-p4r4MIhKk:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/dZ4vUjCZlqQ" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Architecture/default.aspx">Architecture</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/11/02/me-myself-and-design-patterns.aspx</feedburner:origLink></item><item><title>Design for testability - WCF proxies</title><link>http://feedproxy.google.com/~r/vuscode/~3/g2eVk9K4iiI/design-for-testability-wcf-proxies.aspx</link><pubDate>Sun, 01 Nov 2009 00:39:45 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1223</guid><dc:creator>malovicn</dc:creator><slash:comments>11</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1223</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/11/01/design-for-testability-wcf-proxies.aspx#comments</comments><description>&lt;p&gt;Recently I spent some time participating in projects involving Silverlight, Prism etc and there are couple of interesting things I’ve came up with during that period which I would like to share with the community in a form of a couple of blog posts showing the “enhancements” I did in our &lt;a href="http://compositewpf.codeplex.com/" target="_blank"&gt;Prism&lt;/a&gt; based implementation.&lt;/p&gt;  &lt;p&gt;I was thinking a lot where to start and as a result of that I have decided to start with something small but useful. I’ll focus in this blog post on Silverlight, but this simple trick is usable in any other client technology making WCF calls. So, here we go… &lt;/p&gt;  &lt;h1&gt;How to have testable Silverlight code depending on WCF calls&lt;/h1&gt;  &lt;h2&gt;Why reinventing the wheel?&lt;/h2&gt;  &lt;p&gt;In order to make sure that trivial thing I’ll be writing about today was not already covered by someone I did my &lt;a href="http://www.bing.com" target="_blank"&gt;Bing&lt;/a&gt; homework and came out with two approaches you might want to check out:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://dimecasts.net/Casts/ByAuthor/Derik%20Whittaker"&gt;Derik Whittaker&lt;/a&gt; adapter based solution &lt;a title="http://dimecasts.net/Casts/CastDetails/147" href="http://dimecasts.net/Casts/CastDetails/147"&gt;Abstracting away Dependencies for Simpler code&lt;/a&gt;&amp;#160; &lt;/li&gt;    &lt;li&gt;Fake host based solution &lt;a title="http://www.silverlightshow.net/items/Deep-dive-into-WCF-part-1-TDD.aspx" href="http://www.silverlightshow.net/items/Deep-dive-into-WCF-part-1-TDD.aspx"&gt;http://www.silverlightshow.net/items/Deep-dive-into-WCF-part-1-TDD.aspx&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;While I find both of them to be perfectly acceptable solution I think they are suboptimal due to different reasons. &lt;/p&gt;  &lt;p&gt;In case of first solution (which based on screen cast comments is the way a lot of people do) there is one more layer of abstraction to be maintained.    &lt;br /&gt;In typical DDD style application we have DB tables mapped to domain entities which are (usually) flattened in web server layer where the WCF service contracts behave as application level services with client centric shapes and behaviors. With this approach we need another interface with either its own behaviors or just copy pasting the service contract and additional adapter class which delegates the calls to proxy. IMHO, layer of abstraction down –&amp;gt; maintainability level up :)&lt;/p&gt;  &lt;p&gt;In case of second solution, my objections are similar to the one I have &lt;a href="http://blog.vuscode.com/malovicn/archive/2009/10/20/say-no-to-servicelocator.aspx"&gt;regarding service locator&lt;/a&gt;. Abstracting the “locator” (servicehost) leads to opaque dependencies on a consumer level which are much harder to be unit tested and understood. On top of that, I find this solution also to introduce additional complexity with defining factories, providers etc is IMHO are overkill for simple “TDD enable WCF proxy dependable code”&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;Duct tape programmer solution&lt;/h2&gt;  &lt;p&gt;Regardless of how much I disagree with Joel on the &lt;a href="http://www.joelonsoftware.com/items/2009/09/23.html"&gt;value of the duct tape programmer&lt;/a&gt;, I couldn’t get away from the fact that my solution compared with other two (full of big patterns and cool code) looks exactly like it is been done by the duct tape programmer – me. :) That’s ok, simplicity is #1 design criteria for me.&lt;/p&gt;  &lt;p&gt;In this solution I won’t be using therefore any patterns but instead I would just rely on one hack and one small convention to get quickly testable code which is easier to be maintained and understood (compared to other approaches).&lt;/p&gt;  &lt;h1&gt;Demoware “WCF proxy being called directly” sample&lt;/h1&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_3A90888E.png"&gt;&lt;img style="border-right-width:0px;margin:0px 20px 0px 0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" align="left" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_1D3B30C4.png" width="181" height="244" /&gt;&lt;/a&gt; So, here’s the setup for today post. We are having application which goal is to show the names of the users having salary greater then $1000. &lt;/p&gt;  &lt;p&gt;Client is implemented using Silverlight accessing the user data on a server side by making a WCF service calls.&lt;/p&gt;  &lt;p&gt;In order to do that I used vanilla Silverlight solution (didn’t want to use Prism here) consisting of two projects: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Web application containing a UserService.svc WCF service and hosting a silverlight app. &lt;/li&gt;    &lt;li&gt;Silverlight application which has UserService service proxy and MainPage showing the names of users in a ListBox.      &lt;br /&gt;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h3&gt;UserService.svc&lt;/h3&gt;  &lt;pre class="c-sharp"&gt;using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SilverlightApplication.Web
{
    [ServiceContract(Namespace = &amp;quot;http://blog.vuscode.com/200911&amp;quot;)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService
    {
        [OperationContract]
        public Collection&amp;lt;User&amp;gt; GetUsers()
        {
            return new Collection() 
            { 
                new User { Id = 1, Name = &amp;quot;Nikola&amp;quot;, Salary = 1000 },
                new User { Id = 2, Name = &amp;quot;John&amp;quot;, Salary = 2000 },
                new User { Id = 3, Name = &amp;quot;Jane&amp;quot;, Salary = 3000 },

            };
        }
    }

    [DataContract]
    public class User
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public decimal Salary { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;Nothing important here: In one file OperationContract defining a method GetUsers returning the collection of users (User DataContratct being defined in the same file)&lt;/p&gt;

&lt;p&gt;Let’s move on…&lt;/p&gt;

&lt;h3&gt;MainPagePresenter? Where’s the MainPageViewModel?&lt;/h3&gt;

&lt;p&gt;Well, I was surprised that many people I spoke with recently think MVVM is not the only “right” way to do Silverlight\WPF development and I tend to disagree with that. While MVVM has its own values (it is also presentation pattern of my choice too) you can do MVC or MVP (both passive view and supervising controller) equally successfully like you can do it in desktop applications (speaking of which, Silverlight for me is desktop app deployed through browser) If you don’t trust me, ask &lt;a href="http://codebetter.com/blogs/jeremy.miller/"&gt;Jeremy&lt;/a&gt;. That’s why I ended with some implementation for this &lt;/p&gt;

&lt;p&gt;So, in order to spice up this blog post a bit I ended with MVP- like implementation with MainPagePresenter implemented like this&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;

namespace SilverlightApplication
{
    public class MainPagePresenter
    {
        private FrameworkElement view;
        
        public MainPagePresenter(FrameworkElement view)
        {
            this.view = view;
        }

        public void Init() 
        {
            UserServiceClient proxy = new UserServiceClient();
            proxy.GetUsersCompleted += (sender, e) =&amp;gt;
                                       {
                                           this.view.DataContext = e.Result.Where(p =&amp;gt; p.Salary &amp;gt; 1000);
                                       };
            proxy.GetUsersAsync();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Constructor here is more interesting because it accepts the instance with type inheriting from FrameworkElement (pretty much most of controls in Silverlight) and stores its pointer to a view filed. In other words, abstraction of a view is being injected into the presenter just instead of the IView I am being smart here and using the FrameworkElement as abstraction&amp;#160; every view (user control implements).&lt;/p&gt;

&lt;p&gt;It is the good old demoware type of code you’ve seen on a lot of places with proxy being instantiated in the method body spiced up with cool lambda implementation of async event handler (which any better presenter would use to scare the session attendees) and with a simple linq statement filtering the result set to exclude the rows lower then 1000.&lt;/p&gt;

&lt;p&gt;The magic in this code starts when view FrameworkElement.DataContext gets set by the filtered result set. Presenter doesn’t have a clue about what specific control view is but still it is able to set its common property to a value generating desired view behavior.&lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;Wiring&amp;#160; up the view and the presenter&lt;/h3&gt;

&lt;p&gt;There’s really big religious war on the IT sky regarding who is created first (view or viewmodel \ presenter) and the allowed level of coupling between them. I have my own take on that to which I would dedicate a separate blog post (it is important subject) but for the sake of this blog post let say that it is perfectlly fine that view is created first and that it has direct reference to presenter.&lt;/p&gt;

&lt;p&gt;That’s how the view (MainPage.xaml file) ended being implemented like this&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {
        MainPagePresenter presenter;

        public MainPage()
        {
            InitializeComponent();
            this.presenter = new MainPagePresenter(this);
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.presenter.Init();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see in a page constructor a instance of the presenter was created with a pointer to the page itself being passed to presenter (which if you look up would be held as a presenter field and used in Init method).&lt;/p&gt;

&lt;p&gt;Then Loaded event handler is being created (don’t put any UI related code in the constructor because it is not guaranteed that UI would be ready when that line would be executed) and in it presenter.Init() method invoked. In other word, view said to presenter “Please set me up!”&lt;/p&gt;

&lt;h3&gt;Markup code&lt;/h3&gt;

&lt;p&gt;Did I tell you how much I like Wpf\Silverlight? Check the simplicity of the markup code!&lt;/p&gt;

&lt;pre class="xml"&gt;    &amp;lt;Grid x:Name=&amp;quot;LayoutRoot&amp;quot; Background=&amp;quot;White&amp;quot;&amp;gt;
        &amp;lt;ListBox
                 Name=&amp;quot;listBox1&amp;quot;
                 ItemsSource=&amp;quot;{Binding}&amp;quot;
                 DisplayMemberPath=&amp;quot;Name&amp;quot; /&amp;gt;
    &amp;lt;/Grid&amp;gt;&lt;/pre&gt;

&lt;p&gt;Setting ItemsSource to {Binding} effectively said to control “Bind to your own DataContext” (&lt;u&gt;&lt;strong&gt;key moment specific to WPF\SL&lt;/strong&gt;&lt;/u&gt;), and DisplayMemeberPath Name value can be read “whatever the collection would be in DataContext, collection item would have a property called Name”&lt;/p&gt;

&lt;p&gt;Simple, elegant and powerful!&lt;/p&gt;

&lt;h3&gt;Runtime experience&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_7BDB8B27.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_4977B7A8.png" width="244" height="56" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wow, so much talk about such a simple thing. Ok, I proved it working&lt;/p&gt;

&lt;h1&gt;My duct tape based solution&lt;/h1&gt;

&lt;p&gt;is based on the simplest possible solution I was expecting that WCF supports out of box: IXYZServiceClient interface contracting in abstract way proxy behavior.&amp;#160; &lt;/p&gt;

&lt;p&gt;To my surprise I have realized that WCF generated proxy is not creating that interface (IUserServiceClient in this example) so I decided to created in manually.&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Doing things WCF team should have already done&lt;/h2&gt;

&lt;p&gt;I’ve clicked on Show All files icon (to see hidden proxy files) and opened Reference.cs file containing proxy c# code.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_69269170.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5A7BE58B.png" width="244" height="238" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Then I found UserServiceClient class definition&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_3FCF4972.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5F11F045.png" width="619" height="168" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Right click it and pick to extract interface (R# can help with this too)&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_453DBA16.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_7942339C.png" width="950" height="217" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;I pick only the members I care to be abstracted (leaving unchecked all of the WCF infrastructure members)&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_0CEF1D31.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_569DF521.png" width="547" height="379" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;and ended with this&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_2A14C53B.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_026E4911.png" width="244" height="228" /&gt;&lt;/a&gt; &lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_52D02A84.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_317084E8.png" width="644" height="70" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Obviously not good solution because next proxy refresh and all this is gone, so there are two problems: &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;How to preserve interface &lt;/li&gt;

  &lt;li&gt;How to avoid having manually to add interface implementation to generated ServiceClient class. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In order to solve problem #1, I have created then a folder with the same name as the proxy and drag and drop the interface to that folder. First problem solved!&lt;/p&gt;

&lt;p&gt;In order to solve problem #2, I am utilizing the fact that the ServiceClient is generated as partial class so I create in the new folder&amp;#160; another partial UserServiceClient class implementing the IUserServiceClient interface. Here’s how that class look like&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace SilverlightApplication.UserServiceProxy
{
    public partial class UserServiceClient : IUserServiceClient
    {
    }
}&lt;/pre&gt;

&lt;p&gt;I hope now you can get the reason why I was a folder with the same name as the proxy –&amp;gt; the namespaces of types and interfaces in that folder are matching out of the box the ones in the proxy class&lt;/p&gt;

&lt;p&gt;And here&amp;#39;s the solution (for visual learners like me) &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_56FA0249.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_1D76F252.png" width="216" height="163" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;To summarize the solution:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I’ve created the IServiceClient by simple extracting the facade of the proxy client interface &lt;/li&gt;

  &lt;li&gt;I’ve created partial UserServiceClient which is only attaching the interface to proxy &lt;/li&gt;

  &lt;li&gt;Both of files are&amp;#160; not destroyed with proxy regeneration. &lt;/li&gt;

  &lt;li&gt;If the WCF service contract changes over the time, regenerating of new IUserServiceClient is trivial task taking less then 15 seconds. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Duct tape solution at its best! :)&lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h2&gt;Modifying presenter&lt;/h2&gt;

&lt;pre class="c-sharp"&gt;using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;

namespace SilverlightApplication
{
    public class MainPagePresenter
    {
        private FrameworkElement view;
        private IUserServiceClient userServiceClient;
        
        public MainPagePresenter(FrameworkElement view, IUserServiceClient userServiceClient)
        {
            this.view = view;
            this.userServiceClient = userServiceClient;
        }

        public void Init() 
        {
            this.userServiceClient.GetUsersCompleted += (sender, e) =&amp;gt;
                                       {
                                           this.view.DataContext = e.Result.Where(p =&amp;gt; p.Salary &amp;gt; 1000);
                                       };
            this.userServiceClient.GetUsersAsync();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can tell I’ve made two changes:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;added another parameter to the constructor injecting the newly created IUserServiceClient interface &lt;/li&gt;

  &lt;li&gt;Modified Init method to replace proxy instantiation with usage of injected client proxy abstraction. &lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Modifying the view&lt;/h2&gt;

&lt;p&gt;Usually I wouldn’t modify the view but instead rely on IoC container to inject the UserServiceClient instance, but in order to keep this post focused I won’t be using IoC here (you’ll see it in one of my future posts showing my Prism enhancements) so I needed to make a simple change in a page constructor&lt;/p&gt;

&lt;pre class="c-sharp"&gt;        public MainPage()
        {
            InitializeComponent();
            this.presenter = new MainPagePresenter(this, new UserServiceClient());
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }&lt;/pre&gt;

&lt;p&gt;Nothing special, just added new UserServiceClient() to the parameters being passed to a presenter.&lt;/p&gt;

&lt;h2&gt;Running the app again &lt;/h2&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_4AF81215.png"&gt;&lt;img style="border-right-width:0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5B900D03.png" width="244" height="81" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Yeap, still works :)&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Where’s the unit test?&lt;/h2&gt;

&lt;p&gt;Well, this blog post is long enough (and it is late enough :)) so I would skip the unit test example this time because it is fairly trivial to be written now when we have interface of the service proxy. &lt;/p&gt;

&lt;h2&gt;Summary&lt;/h2&gt;

&lt;p&gt;In this blog post I showed another way how to easy introduce a layer of simple abstraction between the WCF service proxy and the code consuming it. &lt;/p&gt;

&lt;p&gt;I find the advantage of my approach VS the two of others in its simplicity and maintainability but again considering I “invented it” that comes as no surprise to me :)&lt;/p&gt;

&lt;p&gt;Source code of the end solution can be downloaded from &lt;a href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/TDDwithWCF.zip" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:381e4720-8efe-42f9-8ae2-cecc6dfd5f44" class="wlWriterEditableSmartContent"&gt;del.icio.us Tags: &lt;a href="http://del.icio.us/popular/WCF" rel="tag"&gt;WCF&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/TDD" rel="tag"&gt;TDD&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/Silverlight" rel="tag"&gt;Silverlight&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/DFT" rel="tag"&gt;DFT&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1223" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=g2eVk9K4iiI:By7TZfP3dVc:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=g2eVk9K4iiI:By7TZfP3dVc:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=g2eVk9K4iiI:By7TZfP3dVc:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=g2eVk9K4iiI:By7TZfP3dVc:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/g2eVk9K4iiI" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://blog.vuscode.com/malovicn/archive/tags/Test+Driven+Development/default.aspx">Test Driven Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/11/01/design-for-testability-wcf-proxies.aspx</feedburner:origLink></item><item><title>Say no to ServiceLocator</title><link>http://feedproxy.google.com/~r/vuscode/~3/BKSczMlobpU/say-no-to-servicelocator.aspx</link><pubDate>Tue, 20 Oct 2009 13:18:17 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1190</guid><dc:creator>malovicn</dc:creator><slash:comments>7</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1190</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/10/20/say-no-to-servicelocator.aspx#comments</comments><description>&lt;p&gt;&lt;strong&gt;&lt;img style="display:inline;margin-left:0px;margin-right:0px;" align="right" src="http://www.pioneerclubs.org/lrc/clipart/large/just_say_no_3.jpg" width="240" height="168" alt="" /&gt; (&lt;/strong&gt;&lt;em&gt;&lt;strong&gt;Disclaimer:&lt;/strong&gt; As I stated &lt;/em&gt;&lt;a title="dependency injection in real world" href="http://blog.vuscode.com/malovicn/archive/2008/12/23/dependency-injection-in-real-world.aspx" target="_blank"&gt;&lt;em&gt;here&lt;/em&gt;&lt;/a&gt;&lt;em&gt;, while I find over the time ServiceLocator based code to be a bad practice, I do understand the need for its usage in certain brown-field&amp;#160; scenarios as a way of reducing the risk while introducing the IoC.)&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;In my previous &lt;a title="Inversion Of Control, Single Responsibility Principle and Nikola’s laws of dependency injection" href="http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx"&gt;Nikola’s laws of dependency injection&lt;/a&gt; blog post I stated couple of IoC laws based on my experience:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Store in IoC container only services. Do not store any entities. &lt;/li&gt;    &lt;li&gt;Any class having more than 3 dependencies should be questioned for SRP violation &lt;/li&gt;    &lt;li&gt;Every dependency of the class has to be presented in a transparent manner in a class constructor. &lt;/li&gt;    &lt;li&gt;Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies. &lt;/li&gt;    &lt;li&gt;IoC container should be explicitly used only in Bootstrapper.      &lt;br /&gt;Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The #5 (“IoC container should be a ghost even in unit tests”) resulted with couple of blog post comments and emails asking for clarification what I mean by that.&lt;/p&gt;  &lt;p&gt;In short:&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Say no to Service Locator \ Opaque dependencies!&lt;/h1&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_71B3EA5C.png"&gt;&lt;img style="border-right-width:0px;margin:0px 40px 0px 0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" align="left" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_2FB46B87.png" width="146" height="244" /&gt;&lt;/a&gt;&lt;a title="Radenko Zec" href="http://blog.developers.ba" target="_blank"&gt;Radenko Zec&lt;/a&gt; posted in comment example which with very slight modifications (to reflect better my Law #1) looks like this…&lt;/p&gt;  &lt;p&gt;There are 4 projects in the solution used in today blog post: &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;ClassLibrary &lt;/strong&gt;containing the two classes where:       &lt;br /&gt;- UserRepository is having dependency on other       &lt;br /&gt;- LoggingService (implementing the ILoggingService) &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;ConsoleApplication1 &lt;/strong&gt;simulating the production usage and containing the:       &lt;br /&gt;- bootstrapper class (defining IoC mappings) and the       &lt;br /&gt;- Program.cs (main console file which would execute our functionality &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;Infrastructure &lt;/strong&gt;containing my naive implementation of Unity container adapter with the       &lt;br /&gt;- IContainer abstraction of the Unity container,       &lt;br /&gt;- UnityContainerAdapter class implementing the &lt;a title="adapter design pattern" href="http://blog.vuscode.com/malovicn/archive/2008/07/30/model-view-presenter-tips-from-trenches-tft-base-types-part-1.aspx" target="_blank"&gt;adapter design pattern&lt;/a&gt; adapting the UnityContainer to IContainer&amp;#160; &lt;br /&gt;- UnityContainer service locator class, &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;TestProject1 &lt;/strong&gt;containing the unit test for the ClassClibrary1 - UserRepositoryTest &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Before diving into the Radenko’s sample implementation let me restate my point by saying that &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;none of the classes using IoC (in this simple example UserRepository) should NOT be aware at all of IoC and &lt;/li&gt;    &lt;li&gt;UserRepositoryTest should NOT have test\fixture setup methods filling the container &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&lt;/p&gt;  &lt;h2&gt;Service locator based implementation&lt;/h2&gt;  &lt;p&gt;As given in &lt;a title="Radenko Zec" href="http://blog.developers.ba" target="_blank"&gt;Radenko&lt;/a&gt;’s comment example Bootstrapper class registers the mappings&lt;/p&gt;  &lt;pre class="c-sharp"&gt;namespace ConsoleApplication1
{
    using ClassLibrary1;
    using Infrastructure;

    public static class Bootstraper
    {
        public static void SetUp()
        {
            IContainer cont = UnityContainer.Instance();
            cont.Register&amp;lt;ILoggingService, Loggingservice&amp;gt;();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Here’s the simple implementation of that LoggingService (not very important for this blog post but still to be clear)&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace ClassLibrary1
{
    using System;
    using System.Diagnostics;

    public class LoggingService : ILoggingService
    {
        public void Log(string message)
        {
            Debug.WriteLine(string.Format(&amp;quot;LOGGED: {0}.&amp;quot;, message));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;And here’s the class being dependable on that LoggingService&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace ClassLibrary1
{
    using Infrastructure;

    public class UserRepository
    {
        public void Delete (int userId)
        {
            IContainer cont = UnityContainer.Instance();
            ILoggingService loggingService = cont.Resolve&amp;lt;ILoggingService&amp;gt;();
            loggingService.Log(string.Format(&amp;quot;User with id:{0} deleted&amp;quot;, userId));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;So, as you can see in a given example Delete method is implemented like this:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;get ServiceLocator (singleton instance of the UnityContainerAdapter) &lt;/li&gt;

  &lt;li&gt;using the ServiceLocator retrieve from IoC container component mapped to ILoggingService &lt;/li&gt;

  &lt;li&gt;use that component to log a message. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;&lt;em&gt;What is wrong with this code?&lt;/em&gt;&lt;/strong&gt;&lt;/u&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It violates the Separation of Concerns \Single Responsibility Principle&amp;#160; – UserRepository taking care about IoC, instance resolution etc &lt;/li&gt;

  &lt;li&gt;It good example of &lt;a title="opaque dependency injection" href="http://blog.vuscode.com/malovicn/archive/2008/06/08/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx" target="_blank"&gt;opaque dependency injection&lt;/a&gt; which hides sometime the set of dependencies component has. 

    &lt;br /&gt;Looks like “not a big deal” but when you face the class with couple of thousands of lines and you have to read them ALL just to get the list and repeat that couple of times, it is a big deal. (Yes, I do agree with you that having that long classes is atrocity of its own kind, but seeing it all the time in my world) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(Couple of more reasons but let’s just continue our journey…)&lt;/p&gt;

&lt;p&gt;Here’s how the p&lt;strong&gt;roduction usage&lt;/strong&gt; would look in this example&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace ConsoleApplication1
{
    using ClassLibrary1;

    class Program
    {
        static void Main(string[] args)
        {
            Bootstraper.SetUp();
            UserRepository userRepository = new UserRepository();
            userRepository.Delete(3);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;No magic there: code issues a command to bootstrapper to initialize IoC, create a instance of UserRepository and invoke its Delete method.&lt;/p&gt;

&lt;p&gt;The last thing left is the example of unit test one might write with this code&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace TestProject1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using ClassLibrary1;
    using Infrastructure;
    using Rhino.Mocks;

    [TestClass]
    public class UserRepositoryTest
    {
        private ILoggingService loggingService;

        [TestInitialize]
        public void Would_Be_Executed_Before_Every_Test()
        {
            var serviceLocator = UnityContainer.Instance();
            loggingService = MockRepository.GenerateMock&amp;lt;ILoggingService&amp;gt;();
            serviceLocator.Register(loggingService);
        }


        [TestMethod]
        public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
        {
            // arrange
            var userId = 3;
            loggingService.Expect(p =&amp;gt; p.Log(string.Empty)).IgnoreArguments();

            // act
            UserRepository userRepository = new UserRepository();
            userRepository.Delete(userId);

            // assert
            this.loggingService.VerifyAllExpectations();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;This is not a blog post on unit testing so just a short discussion what the test does :&lt;/p&gt;

&lt;p&gt;In Test initialization the singleton instance of IoC containe is retrieved. Then an RhinoMock dynamic mock class of ILoggingService is created and then injected into the container. Summarized: we stored something in a container before the test execution, because we know from the source code that it would be used in SUT.&lt;/p&gt;

&lt;p&gt;The test itself is very simple:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Arrange defines what is the expected behavior of the logging service which is supposed to be caused as a result of SUT activity &lt;/li&gt;

  &lt;li&gt;Act creates an instance of the UserRepository and invokes the delete method &lt;/li&gt;

  &lt;li&gt;Arrange verifies that the expected behavior of the logging service occurred. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nothing much –&amp;gt; just another example of behavior unit testing.&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;What is wrong with this unit test?&lt;/h2&gt;

&lt;p&gt;Well, I wrote them “a few” like this and it works well but with certain pain points which the more test you write the more painful become:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;It prevents black box unit testing. 
    &lt;br /&gt;I tend lately to think about unit tests more as of a functional specifications and due to that I try always to test the class based on defined functional requirements WITHOUT looking in the implementation (to stay as objective as I can). Only once I cover ALL functional cases, I tend to do a quick check of the test coverage and focus on removing the code not being tested (all reqs satisfied and code not used –&amp;gt; potential overkill) &lt;/li&gt;

  &lt;li&gt;Prevents effective unit testing 
    &lt;br /&gt;Sooner or later, with this code you end with writing test following the “run the test, get what is missing, add a mapping, run it again, get what is missing, add a line…”&amp;#160; which IMHO ends to be very slow process. &lt;/li&gt;

  &lt;li&gt;Makes Fixture&amp;#39;\SetUp very big and clunky. 
    &lt;br /&gt;Here we set up one dependency, but imagine hundreds of unit tests with their own many dependencies dig up in the code and how big this section would become… 

    &lt;br /&gt;In the past I was trying to tackle that by creating special bootstrapper classes filling the IoC container with test infrastructure stubs and with using AutoMockingContainer (still not completely sure about should I do that or not – another blog post) but the end result is that I got more code to be maintained and which is getting broken wevery time production interfaces change etc. &lt;/li&gt;

  &lt;li&gt;Decreases test readability 
    &lt;br /&gt;If you want take tests as a sort of functional specification (and you should) pretty often you would want to “read the tests” in order to get what and how the SUT works. Having a bunch of setup code outside of the method being read makes that much harder. &lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;All the right solutions are &lt;b&gt;always &lt;/b&gt;simple as possible&lt;/h2&gt;

&lt;p&gt;In order to comply to law #5 I need to refactor the UserRepository implementation by removing IoC container from it and in order to comply law #3 I need to explicitly enlist in a constructor all of its dependencies.&lt;/p&gt;

&lt;p&gt;So, following those two rules I end with this code:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace ClassLibrary1
{
    public class UserRepository
    {
        private readonly ILoggingService loggingService;

        public UserRepository(ILoggingService loggingService)
        {
            this.loggingService = loggingService;
        }

        public void Delete (int userId)
        {
            this.loggingService.Log(string.Format(&amp;quot;User with id:{0} deleted&amp;quot;, userId));
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see all I did was to transform the ServiceLocator type of code to dependency injection type of code where there is no more SoC\SRP violation and where the UserRepository is unaware of IoC (no single line related to it).&lt;/p&gt;

&lt;p&gt;For the folks with concerns that this could result with some very long constructors with too many dependencies I suggest checking out &lt;a title="Unity Auto Mocking Container" href="http://blog.vuscode.com/malovicn/archive/2009/04/04/microsoft-unity-auto-mocking-container.aspx" target="_blank"&gt;Auto Mocking Container&lt;/a&gt; and/or:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Law #2 Any class having more than 3 dependencies should be questioned for SRP violation &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let see the unit test for this class&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace TestProject1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using ClassLibrary1;
    using Rhino.Mocks;

    [TestClass]
    public class UserRepositoryTest
    {
        [TestMethod]
        public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
        {
            // arrange
            var userId = 3;
            
            var loggingService = MockRepository.GenerateMock&amp;lt;ILoggingService&amp;gt;();
            loggingService.Expect(p =&amp;gt; p.Log(string.Empty)).IgnoreArguments();
            // act
            UserRepository userRepository = new UserRepository(loggingService);
            userRepository.Delete(userId);
            
            // assert
            loggingService.VerifyAllExpectations();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see above: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;There is no more initialization routine – all of the code related to this test is in one place. &lt;/li&gt;

  &lt;li&gt;Every test initialize only what it needs (no big chunk of initializing union of&amp;#160; of mappings all tests need) &lt;/li&gt;

  &lt;li&gt;While writing the test the C# compiler informs me that the UserRepository needs a logging service. If I don’t provide it test won’t compile. 
    &lt;br /&gt;That’s how I can avoid looking at the source code in order to get what dependency class has, &lt;/li&gt;

  &lt;li&gt;As for law #5, notice that in my unit test there is NO IoC code at all (even infrastructure component is not referenced anymore). 
    &lt;br /&gt;IoC has to be for us when needed but also it has to stay away from our work. Full &lt;a href="http://www.artima.com/intv/dry3.html" target="_blank"&gt;orthogonality&lt;/a&gt;. Period. &lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;How the production code looks with new approach?&lt;/h2&gt;

&lt;p&gt;Almost the same &lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace ConsoleApplication1
{
    using ClassLibrary1;

    using Infrastructure;

    class Program
    {
        static void Main(string[] args)
        {
            Bootstraper.SetUp();
            var unityContainer = UnityContainer.Instance();

            var userRepository = unityContainer.Resolve&amp;lt;UserRepository&amp;gt;();
            userRepository.Delete(3);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;The main difference is that I’ve used the unity to resolve UserRepository and performs (by that) automatic object graph wire up. It may look like that we ended with the same thing just in other class and that is correct (partially)! &lt;/p&gt;

&lt;p&gt;It is correct in a sense that if you think for a second about the real world systems you have many classes chained in cross dependencies in which case it is in your interest to push out from all of them the IoC resolution and let the IoC container of your choice do the auto wire up magic. &lt;/p&gt;

&lt;p&gt;It is not correct in a sense that in a most part of your system (usually matching the area you want to test( you what have implict injection and not this explicit. For example, if your CompanyRepository would need a UserRepository (not claiming it has real sense to be done) the CompanyRepository would just have in its constructor IUserRepository\UserRepository and that’s it.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Reafactoring from service locator to real dependency injection type of code is very easy if not trivial but do require a small “&lt;a href="http://www.bing.com" target="_blank"&gt;bing&lt;/a&gt;!” in your head to just realize it. 

  &lt;br /&gt;After switching to this practice, my tests get much lighter, faster, easier to read and maintain. &lt;/p&gt;

&lt;p&gt;Radenko, I hope I answered your question :)&lt;/p&gt;

&lt;p&gt;Here’s a &lt;a title="Sample solution" href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/SLBlogPost.zip" target="_blank"&gt;sample code&lt;/a&gt; I used in today’s blog &lt;/p&gt;

&lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:83d6976e-c57d-420d-ba0d-85da48f8e107" class="wlWriterEditableSmartContent"&gt;Technorati Ознаке: &lt;a href="http://technorati.com/tags/TDD" rel="tag"&gt;TDD&lt;/a&gt;,&lt;a href="http://technorati.com/tags/IOC" rel="tag"&gt;IOC&lt;/a&gt;,&lt;a href="http://technorati.com/tags/SRP" rel="tag"&gt;SRP&lt;/a&gt;,&lt;a href="http://technorati.com/tags/DI" rel="tag"&gt;DI&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Unity" rel="tag"&gt;Unity&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1190" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=BKSczMlobpU:FEu2p9VcbEE:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=BKSczMlobpU:FEu2p9VcbEE:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=BKSczMlobpU:FEu2p9VcbEE:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=BKSczMlobpU:FEu2p9VcbEE:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/BKSczMlobpU" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Architecture/default.aspx">Architecture</category><category domain="http://blog.vuscode.com/malovicn/archive/tags/Test+Driven+Development/default.aspx">Test Driven Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/10/20/say-no-to-servicelocator.aspx</feedburner:origLink></item><item><title>Inversion Of Control, Single Responsibility Principle and Nikola’s laws of dependency injection</title><link>http://feedproxy.google.com/~r/vuscode/~3/lbxrV65AhJc/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx</link><pubDate>Fri, 16 Oct 2009 12:04:18 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:1166</guid><dc:creator>malovicn</dc:creator><slash:comments>13</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=1166</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx#comments</comments><description>&lt;p&gt;Today I stumbled upon the stack overflow question regarding &lt;a title="using DI frameworks for classes with many dependencies" href="http://stackoverflow.com/questions/194534/using-dependency-injection-frameworks-for-classes-with-many-dependencies/" target="_blank"&gt;using DI frameworks for classes with many dependencies&lt;/a&gt; where the example given and couple of answers have reminded me about a subject I want to post for a long time.&lt;/p&gt;  &lt;p&gt;So the example from question basically goes like this:&lt;/p&gt;  &lt;pre class="c-sharp"&gt;MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)&lt;/pre&gt;
// ... versus ...
&lt;pre class="c-sharp"&gt;ILog log = DIContainer.Get&amp;lt;ILog&amp;gt;();&lt;/pre&gt;

&lt;p&gt;And the 3 questions related to this example are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;How to avoid passing those common but uninteresting dependencies interfaces to every class? &lt;/li&gt;

  &lt;li&gt;How do you approach dependencies that &lt;em&gt;might&lt;/em&gt; be used, but may be expensive to create? &lt;/li&gt;

  &lt;li&gt;How to build object graph of MyClass considering the fact that any of those dependencies can have their own dependencies etc.. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So, let’s start and keep it short…&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h2&gt;What is wrong fundamentally with his example?&lt;/h2&gt;

&lt;p&gt;Being a big proponent of DDD principles as the one leading to clean and maintainable design, I found the design of the question example is wrong in a sense that an entity (which MyClass is) should NOT have dependencies on infrastructure (or any other) services. &lt;/p&gt;

&lt;p&gt;Related to that is &lt;strong&gt;Nikola’s 1st law of IoC&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Store in IoC container only services. Do not store any entities.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I strongly believe that if the author of example was following that principle he wouldn’t be in the position to ask the question he did ask.&amp;#160; &lt;/p&gt;

&lt;p&gt;Second thing I learned in past years to detect as wrong in code like the one in example is the high number of dependencies in a constructor which usually in my experience points to SRP (Single Responsibility Principle) violations and low SOC (Separation of Concerns) in code. The example is not showing the code of the MyClass but (based on my experience) I am pretty sure it can be broken to couple of coherent SRP separate classes where each one of them would have very few (if any) number of dependencies&lt;/p&gt;

&lt;p&gt;Related to that is &lt;strong&gt;Nikola’s 2nd law of IoC&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;&amp;quot;Any class having more then 3 dependencies should be questioned for SRP violation&amp;quot;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Basically all answers on the question are agreeing that second approach is worst (together with me) because burring up the dependencies a class has prevents effective black box unit testing and makes harder refactoring. I already blogged about&amp;#160; &lt;a title="transparent vs opaque dependency injection" href="http://blog.vuscode.com/malovicn/archive/2008/06/08/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx" target="_blank"&gt;transparent vs. opaque DI&lt;/a&gt;, so I’ll skip beating the dead horse here.&lt;/p&gt;

&lt;p&gt;The thing I do want here to discuss are the answers which are recommending in general replacing the first case with the single dependency on IServiceLocator\IContainer. &lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;IServiceLocator\IContainer injection doesn’t make a lot of sense in general&lt;/h3&gt;

&lt;p&gt;There is no real advantage of using the IServiceLocator vs the DIContainer from the second solution. I mean we would be decoupled from the specific IoC container but the problems of low testability and hard refactoring would stay due to the same opaque nature of dependencies class has. In other words, from my point of view using singleton service locator in this sense is even better then the IServiceLocator being injected (same set of problems, one parameter less in constructor).&lt;/p&gt;

&lt;p&gt;The only exception from this rule is the case when we have multiple components mapped to a service with a different key (IoC version of Strategy pattern implementation) there is no way to inject the one with a given key (as long they share the same interface) so injecting IContainer in that case is acceptable.&lt;/p&gt;

&lt;h3&gt;Setter type of dependency injection shouldn’t be used&lt;/h3&gt;

&lt;p&gt;Second type of answer is not to use constructor dependency injection but instead setter type of DI (I’ve blogged about the differences &lt;a title="Dependency injection and sevice locator" href="http://blog.vuscode.com/malovicn/archive/2007/01/19/dependency-injection-and-service-locator.aspx" target="_blank"&gt;long time ago&lt;/a&gt;). Couple a years ago I was fan of the setter type from the same reasons (removes the constructor noise) but the set of problems I was facing in real world related to it convince me that it is much worse choice then the constructor type. The main reasons behind that opinion are primarily due to the facts that setter type of DI makes dependencies again opaque and (in this case) even more important result with creation of public API members which only purpose is to satisfy infrastructure needs which (I believe) is deeply wrong. No API members should be created just in order to satisfy the infrastructure and\or unit testing needs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nikola’s 3rd law of IoC&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Every dependency of the class has to be presented in a transparent manner in a class constructor.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;Factories and IoC&lt;/h3&gt;

&lt;p&gt;The question contains a thought of injecting the factory interface which reminded me also on a discussion I had with one of my colleagues regarding usage of factories in certain scenarios (as proposed in &lt;a title="Art Of Unit Testing" href="http://www.manning.com/osherove/" target="_blank"&gt;Art Of Unit Testing&lt;/a&gt; – go buy that book in case you haven’t done that already). &lt;/p&gt;

&lt;p&gt;IMO, using factories together with IoC doesn’t make a lot of sense because IoC container is in a sense “universal abstract factory”. &lt;/p&gt;

&lt;p&gt;In other words, in my experience any time I thought about adding a factory I ended with much simpler IoC based solution so that’s why I would dare to say that &lt;a title="IoC kill the Factory star" href="http://en.wikipedia.org/wiki/Video_Killed_the_Radio_Star" target="_blank"&gt;“IoC kill the Factory star&amp;quot;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;&lt;/h3&gt;

&lt;h3&gt;Q2: How do you approach dependencies that &lt;em&gt;might&lt;/em&gt; be used, but may be expensive to create?&lt;/h3&gt;

&lt;p&gt;Very simple, don’t create them to be like that. A constructor of a class being resolved from a IoC should be as light as possible just defining (if any) its own dependencies. Any class initialization or implementation shouldn’t be implicitly triggered from constructor but instead explicitly by invoking a specific member on instance resolved from a container. That’s how resolving all of them could be done without any significant performance issues.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nikola’s 4th law of IoC&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;Q3: How to build object graph of MyClass?&lt;/h3&gt;

&lt;p&gt;Without going into the details of how to do this with given framework (which other did in the SO answers and I covered it for Unity &lt;a title="Microsoft Unity auto building up of object graph" href="http://blog.vuscode.com/malovicn/archive/2008/05/18/design-for-testability-microsoft-unity-part-7.aspx" target="_blank"&gt;here&lt;/a&gt;) I would like to emphasize again the need for moving the mapping definition and resolution from UI elements (as proposed as option question) to dedicated application bootstrapper class\component&amp;#160; which (implementing the Builder design pattern) sole responsibility would be to define the mappings in a single place or orchestrating other component bootstrappers. &lt;/p&gt;

&lt;p&gt;On the beginning of the application life cycle, bootstrapper would build up the dependencies removing (ideally) the need for other parts of code base to be aware of the IoC container awareness. &lt;/p&gt;

&lt;p&gt;(More about Builder pattern in dusty but still good &lt;a title="Builder design pattern" href="http://codebetter.com/blogs/jeremy.miller/archive/2006/03/09/140465.aspx" target="_blank"&gt;Jeremy’s blog post&lt;/a&gt;) &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nikola’s 5th law of IoC&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;IoC container should be explicitly used only in Bootstrapper. Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container.&amp;quot;&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Appendix&lt;/h2&gt;

&lt;p&gt;So here we go, my dear reader – my first blog post in a while. I decided to fight with my Twitter addiction which sucked up all of my blogging energy and to start writing down (in my awful English) the thoughts and experiences I collected in last year so stay tuned for the bunch of very diverse and (hopefully) amusing blog posts&lt;/p&gt;

&lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:ff1b58b6-1e20-444f-b451-9d437e67d329" class="wlWriterEditableSmartContent"&gt;del.icio.us Tags: &lt;a href="http://del.icio.us/popular/IoC" rel="tag"&gt;IoC&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/Inversion+of+controls" rel="tag"&gt;Inversion of controls&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/DI" rel="tag"&gt;DI&lt;/a&gt;,&lt;a href="http://del.icio.us/popular/Dependency+Injection" rel="tag"&gt;Dependency Injection&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=1166" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=lbxrV65AhJc:eq3GbaAAX-Q:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=lbxrV65AhJc:eq3GbaAAX-Q:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=lbxrV65AhJc:eq3GbaAAX-Q:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=lbxrV65AhJc:eq3GbaAAX-Q:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/lbxrV65AhJc" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Architecture/default.aspx">Architecture</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/10/16/inversion-of-control-single-responsibility-principle-and-nikola-s-laws-of-dependency-injection.aspx</feedburner:origLink></item><item><title>And the winner is...</title><link>http://feedproxy.google.com/~r/vuscode/~3/JrzMEz-fIbg/and-the-winner-is.aspx</link><pubDate>Wed, 26 Aug 2009 08:51:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:911</guid><dc:creator>malovicn</dc:creator><slash:comments>0</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=911</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/08/26/and-the-winner-is.aspx#comments</comments><description>&lt;h4&gt;&lt;a href="http://bbits.co.uk/blog/archive/2009/08/19/bloggers-win-a-free-place-for-roy-osheroves-tdd-masterclass-worth-2395.aspx" id="viewpost_ascx_TitleUrl" title="Title of this entry."&gt;Bloggers: Win a free place for Roy Osherove’s TDD Masterclass (worth £2395!)&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of &amp;quot;The Art of Unit Testing&amp;quot; (&lt;a href="http://www.artofunittesting.com/"&gt;http://www.artofunittesting.com/&lt;/a&gt;), a leading tdd &amp;amp; unit testing book; he maintains a blog at &lt;a href="http://iserializable.com/"&gt;http://iserializable.com&lt;/a&gt; (which amoung other things has critiqued tests written by Microsoft for &lt;a href="http://asp.net/"&gt;asp.net&lt;/a&gt; MVC - check out the testreviews category) and has recently been on the Scott Hanselman podcast (&lt;a href="http://bit.ly/psgYO"&gt;http://bit.ly/psgYO&lt;/a&gt;)
where he educated Scott on best practices in Unit Testing techniques.
For a further insight into Roy&amp;#39;s style, be sure to also check out Roy&amp;#39;s
talk at the recent Norwegian Developer&amp;#39;s Conference (&lt;a href="http://bit.ly/NuJVa"&gt;http://bit.ly/NuJVa&lt;/a&gt;).&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Full Details here: &lt;a href="http://bbits.co.uk/tddmasterclass"&gt;http://bbits.co.uk/tddmasterclass&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;bbits
are holding a raffle for a free ticket for the event. To be eligible to
win the ticket (worth £2395!) you MUST paste this text, including all
links, into your blog and email &lt;a href="mailto:Ian@bbits.co.uk"&gt;Ian@bbits.co.uk&lt;/a&gt; with the url to the blog entry.&amp;nbsp; The draw will be made on September 1st and the winner informed by email and on &lt;a href="http://bbits.co.uk/blog"&gt;bbits.co.uk/blog&lt;/a&gt; &lt;/p&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=911" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=JrzMEz-fIbg:kwFUOT9zwpw:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=JrzMEz-fIbg:kwFUOT9zwpw:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=JrzMEz-fIbg:kwFUOT9zwpw:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=JrzMEz-fIbg:kwFUOT9zwpw:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/JrzMEz-fIbg" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/News/default.aspx">News</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/08/26/and-the-winner-is.aspx</feedburner:origLink></item><item><title>Prism (CAL) unit testing - How to test Prism (CAL) Event Aggregator using Rhino Mocks</title><link>http://feedproxy.google.com/~r/vuscode/~3/fuedrrgXicc/prism-cal-unit-testing-how-to-test-prism-cal-event-aggregator-using-rhino-mocks.aspx</link><pubDate>Fri, 17 Apr 2009 22:41:54 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:624</guid><dc:creator>malovicn</dc:creator><slash:comments>4</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=624</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/04/17/prism-cal-unit-testing-how-to-test-prism-cal-event-aggregator-using-rhino-mocks.aspx#comments</comments><description>&lt;h1&gt;&lt;/h1&gt;  &lt;p&gt;I spent some time recently working with &lt;a href="http://www.codeplex.com/CompositeWPF/" target="_blank"&gt;Microsoft Composite Application Guidance (A.K.A. &amp;quot;Prism&amp;quot;, “CAL”)&lt;/a&gt; and I think it is very good platform for building composite UI by either using WPF or Silverlight.&lt;/p&gt;  &lt;p&gt;One of its greatest advantages is that it was done in open source manner which resulted with most of the community feedback being incorporated into lightweight, testing friendly framework. Reference implementation and samples are also good but showing only static stubs based testing which is ok but not as powerful as mocking with some mocking framework. &lt;/p&gt;  &lt;p&gt;My mocking framework of choice is Rhino Mocks and I am going to make couple of simple blog posts showing how to test Prism code using the Rhino Mocks in couple of typical every day scenarios.&lt;/p&gt;  &lt;p&gt;And that leads us to today’s blog post…&lt;/p&gt;  &lt;h1&gt;How to test Prism (CAL) EventAggregator based code using Rhino Mocks?&lt;/h1&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_7041877A.png"&gt;&lt;img style="border-right-width:0px;margin:0px 20px 0px 0px;display:inline;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" title="image" border="0" alt="image" align="left" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_410F9BE3.png" width="256" height="304" /&gt;&lt;/a&gt;&lt;a href="http://en.wikipedia.org/wiki/System_Under_Test" target="_blank"&gt;SUT&lt;/a&gt; I’ll be using today will be as simple as possible to deliver the message. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;LoggingService&lt;/strong&gt; is service which is responsible for handling the logging of system errors in a way that:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;subscribes to system wide events which are requested to be logged without referencing the event sources &lt;/li&gt;    &lt;li&gt;decides if event needs to be published (based on severity) &lt;/li&gt;    &lt;li&gt;if it does, it formats the system event adding the time stamp etc &lt;/li&gt;    &lt;li&gt;calls the publishing service which is handling the publishing of formatted event &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Considering the fact that in my sample we would be having various publishing services in system publishing to different targets(eventlog, flat text file) the LoggingService gets &lt;a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank"&gt;dependency injected&lt;/a&gt; only a component implementing the &lt;strong&gt;IPublishingService. &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;S&lt;/strong&gt;ubscription to system wide events on a decoupled manner is possible through &lt;a href="http://martinfowler.com/eaaDev/EventAggregator.html" target="_blank"&gt;EventAggregator design pattern&lt;/a&gt;&amp;#160; which implementation is in Prism provided through IEventAggregator service. &lt;/p&gt;  &lt;p&gt;The &lt;strong&gt;LogErrorEvent&lt;/strong&gt; is an event to which LoggerService would subscribe and which carries the event argument of &lt;strong&gt;EventData &lt;/strong&gt;type containing the ErrorLevel and ErrorMessage data.&lt;/p&gt;  &lt;h2&gt;&lt;/h2&gt;  &lt;h2&gt;Show me the code&lt;/h2&gt;  &lt;p&gt;Enough of my blabbering (and my English), code will speak for itself much better :)    &lt;br /&gt;    &lt;br /&gt;&lt;em&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;Sample used in today&amp;#39;s blog post can be downloaded &lt;/strong&gt;&lt;/font&gt;&lt;/em&gt;&lt;a href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/Mock%7C_EAG.zip" target="_blank"&gt;&lt;em&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;here&lt;/strong&gt;&lt;/font&gt;&lt;/em&gt;&lt;/a&gt;&lt;em&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;.&lt;/strong&gt;&lt;/font&gt;&lt;/em&gt;&lt;/p&gt;  &lt;h3&gt;LoggingService&lt;/h3&gt;  &lt;pre class="c-sharp"&gt;using System;
using System.Text;
using Microsoft.Practices.Composite.Events;

namespace Example
{
    public class LoggingService
    {
        private readonly IEventAggregator eventAggregator;
        private readonly IPublishingService publishingService;

        public LoggingService(IEventAggregator eventAggregator, IPublishingService publishingService)
        {
            this.eventAggregator = eventAggregator;
            this.publishingService = publishingService;
            this.eventAggregator
                .GetEvent&amp;lt;LogErrorEvent&amp;gt;()
                .Subscribe(this.LogIt);
        }

        private void LogIt(EventData eventData)
        {
            if (eventData.ErrorLevel&amp;lt;=100)
                return;

            var stringBuilder = new StringBuilder();
            stringBuilder
                .AppendFormat(&amp;quot;Date:{0}&amp;quot;, DateTime.Now)
                .AppendLine()
                .Append(eventData.ErrorMessage)
                .AppendLine();
            this.publishingService.PublishError(stringBuilder.ToString());
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Nothing fancy there:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;constructor accepts two parameters which provide to LoggingService access to event aggregator and publishing service through &lt;a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank"&gt;inversion of controls&lt;/a&gt;. &lt;/li&gt;

  &lt;li&gt;in constructor injected event aggregator is used for subscribing of LogIt method to LogErrorEvent. &lt;/li&gt;

  &lt;li&gt;LogIt method is private (wouldn’t work in case of Silverlight – but that is sepa rate blog post) and does next things: 
    &lt;ul&gt;
      &lt;li&gt;makes sure that only events with level greater then 100 get published &lt;/li&gt;

      &lt;li&gt;formats the given error message into appropriate format &lt;/li&gt;

      &lt;li&gt;pass the formatted message to publishing service &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;IPublishingService, LogErrorEvent and EventData&lt;/h3&gt;

&lt;pre class="c-sharp"&gt;namespace Example
{
    public interface IPublishingService
    {
        void PublishError(string errorMessage);
    }
}

using Microsoft.Practices.Composite.Presentation.Events;

namespace Example
{
    public class LogErrorEvent : CompositePresentationEvent
    {
        
    }
}

namespace Example
{
    public class EventData
    {
        public int ErrorLevel { get; set; }
        public string ErrorMessage { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;No need to waste time commenting this…&lt;/p&gt;

&lt;h2&gt;Testing the code &lt;/h2&gt;

&lt;p&gt;I could have done test first etc, but I believe that it would obfuscate the point of this blog , which now once we see the code being tested is going to be just showing the tests&amp;#160; &lt;/p&gt;

&lt;h3&gt;Test 1 – How to make sure that event is getting subscribed&lt;/h3&gt;

&lt;pre class="c-sharp"&gt;        /// 
        /// Shows how to verify that event aggregator subscription occurred.
        ///
        [TestMethod()]
        public void Ctor_Default_WouldSubscribeToLogErrorEvent()
        {
            // arrange
            var publishingServiceStub = MockRepository.GenerateStub&amp;lt;IPublishingService&amp;gt;();
            var eventAggregatorMock = MockRepository.GenerateStub&amp;lt;IEventAggregator&amp;gt;();
            var logErrorEvent = MockRepository.GenerateMock&amp;lt;LogErrorEvent&amp;gt;();

            // event aggregator get event would return mocked log error event 
            eventAggregatorMock.Stub(p =&amp;gt; p.GetEvent&amp;lt;LogErrorEvent&amp;gt;()).Return(logErrorEvent);
            
            // expect that LogErrorEvent would be subscribed in constructor
            logErrorEvent
                .Expect(p =&amp;gt; p.Subscribe(null))
                .Return(null)
                .IgnoreArguments() // we don&amp;#39;t care which exact method or action subscribed, just that there was some.
                .Repeat.Once();

            // act
            var loggingService = new LoggingService(eventAggregatorMock, publishingServiceStub);

            // assert
            logErrorEvent.VerifyAllExpectations();
        }&lt;/pre&gt;

&lt;p&gt;The test is using Rhino Mocks AAA syntax introduced in 3.5 version (if you don’t know it, read &lt;a href="http://ayende.com/Wiki/Rhino+Mocks+3.5.ashx" target="_blank"&gt;Rhino Mocks Documentation Wiki&lt;/a&gt; excellent documentation).&lt;/p&gt;

&lt;p&gt;In Arange section test:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;defines two stubs for the services being used (stubs because I don’t care to set any expectation related to them in this test) &lt;/li&gt;

  &lt;li&gt;defines the mock of the event which subscription I am about to check &lt;/li&gt;

  &lt;li&gt;stubs the event aggregator behavior so on GetEvent&amp;lt;LoggErrorEvent&amp;gt;() method call would return event mock I created. &lt;/li&gt;

  &lt;li&gt;defines expectation on that event mock that subscription would occur once (IgnoreArguments() is there because this test doesn’t care really which method exactly would subscribe to event. Test cares only that subscription had occurred) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In Act section test just constructs the service&lt;/p&gt;

&lt;p&gt;In Assert section test triggers verifying of the event log expectations (which in this test were: someone subscribed to this event)&lt;/p&gt;

&lt;p&gt;(Note that making test for verifying that the Publish have occurred during the test would be pretty much the same as this test with a change on mocked expectations only)&lt;/p&gt;

&lt;h3&gt;Test 2a – How to invoke event aggregator in Act test section&lt;/h3&gt;

&lt;p&gt;Sometimes there is a behavior we want to unit test which is occurring upon the event being published through IEventAggregator and because we can be using anonymous delegate, private method handling the event (case of this blog post) there is no easy way to invoke functionality which is wanted to be tested.&lt;/p&gt;

&lt;p&gt;This test shows how to invoke event aggregator to publish the desired event which would trigger code being tested, &lt;/p&gt;

&lt;p&gt;In case of this example we want to test that not severe errors (error level &amp;lt;= 100) are not getting published.&lt;/p&gt;

&lt;pre class="c-sharp"&gt;        /// 
        /// An example of how to trigger event aggregator in act section
        ///
        [TestMethod()]
        public void LogIt_ErrorLevel100_WouldNotBePublished()
        {
            // arrange
            var logErrorEvent = new LogErrorEvent();
            var publishingServiceMock = MockRepository.GenerateMock&amp;lt;IPublishingService&amp;gt;();
            var eventAggregatorStub = MockRepository.GenerateStub&amp;lt;IEventAggregator&amp;gt;();

            eventAggregatorStub.Stub(p =&amp;gt; p.GetEvent&amp;lt;LogErrorEvent&amp;gt;()).Return(logErrorEvent);
            
            // expect that publishing service would never be called
            publishingServiceMock
                .Expect(p =&amp;gt; p.PublishError(Arg&amp;lt;string&amp;gt;.Is.Anything))
                .Repeat.Never();
            
            // act
            var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
            
            // invoke the event aggregator
            logErrorEvent.Publish(new EventData()
            {
                ErrorLevel = 100,
                ErrorMessage = &amp;quot;Some error message&amp;quot;
            });

           // assert
            publishingServiceMock.VerifyAllExpectations();
        }&lt;/pre&gt;

&lt;p&gt;In this test, test is having in &lt;strong&gt;Arrange &lt;/strong&gt;section:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;An instance of the log error event (not the mock of that event like in the case of previous test example) &lt;/li&gt;

  &lt;li&gt;Mock of the publishing service (in previous test we had stub) because that is service we need to check it won’t be called. &lt;/li&gt;

  &lt;li&gt;Stub of the event aggregator with stubbed GetEvent&amp;lt;LogErrorEvent&amp;gt; method &lt;/li&gt;

  &lt;li&gt;An expectation that PublishError method of the publishing service would never be called (regardless of the parameter being sent to that method) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In &lt;strong&gt;Act&lt;/strong&gt; section test is :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;constructing the logging service injecting the event aggregator stub and mock of publishing service &lt;/li&gt;

  &lt;li&gt;invoking the Publish method on a log error event instance passing the test data (error level == 100 in this test) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In &lt;strong&gt;Assert&lt;/strong&gt; section, we are just triggering checking of expectation defined on mock of the publishing service (no call made to publish error method)&lt;/p&gt;

&lt;h3&gt;Test 2b – How to invoke event aggregator in Act test section&lt;/h3&gt;

&lt;p&gt;Although from perspective of this blog post it doesn’t have a lot of value here’s the test testing that publishing service will be called in case event will be published with error level greater then 100. (The more Rhino Mocks examples we have on web, the better adopting rate will be :))&lt;/p&gt;

&lt;pre class="c-sharp"&gt;	/// 
        /// An example of how to trigger event aggregator in act section
        ///
        [TestMethod()]
        public void LogIt_ErrorLevelGreaterThen100_WouldBePublished()
        {
            // arrange
            var logErrorEvent = new LogErrorEvent();
            var publishingServiceMock = MockRepository.GenerateMock&amp;lt;IPublishingService&amp;gt;();
            var eventAggregatorStub = MockRepository.GenerateStub&amp;lt;IEventAggregator&amp;gt;();

            eventAggregatorStub.Stub(p =&amp;gt; p.GetEvent&amp;lt;LogErrorEvent&amp;gt;()).Return(logErrorEvent);

            publishingServiceMock
                .Expect(p =&amp;gt; p.PublishError(Arg&amp;lt;string&amp;gt;.Matches(param =&amp;gt; param.Contains(&amp;quot;Some error message&amp;quot;))))
                .Repeat.Once();

            // act
            var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
            logErrorEvent.Publish(new EventData()
            {
                ErrorLevel = 101,
                ErrorMessage = &amp;quot;Some error message&amp;quot;
            });
            // assert
            publishingServiceMock.VerifyAllExpectations();
        }&lt;/pre&gt;

&lt;p&gt;Almost the same sample like previous one just with two small differences: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;In arrange section, expectation is that the PublishError method would be called once with a method parameter containing “Some error message” string (inline constrains) &lt;/li&gt;

  &lt;li&gt;In act section, event is published with error level &amp;gt;100 to trigger the positive case when publishing service is been triggered &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Green is nice :)&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_65C0B35A.png"&gt;&lt;img style="border-bottom:0px;border-left:0px;display:inline;border-top:0px;border-right:0px;" title="image" border="0" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_36FAFAB8.png" width="590" height="118" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Conclusion &lt;/h2&gt;

&lt;p&gt;Thanks to P&amp;amp;P team and community feedback, CAL\PRISM event aggregator is implemented in such a way that mocking it is very easy (if not trivial) and every framework enabling easy testing is a good framework for me :) Good work P&amp;amp;P!&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;div style="padding-bottom:0px;margin:0px;padding-left:0px;padding-right:0px;display:inline;float:none;padding-top:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:08f4745d-2fc3-422a-9bcd-ca7c4d2dd8e5" class="wlWriterEditableSmartContent"&gt;Technorati Ознаке: &lt;a href="http://technorati.com/tags/Prism" rel="tag"&gt;Prism&lt;/a&gt;,&lt;a href="http://technorati.com/tags/CAL" rel="tag"&gt;CAL&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Test+Driven+Development" rel="tag"&gt;Test Driven Development&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Mocking" rel="tag"&gt;Mocking&lt;/a&gt;,&lt;a href="http://technorati.com/tags/RhinoMocks" rel="tag"&gt;RhinoMocks&lt;/a&gt;,&lt;a href="http://technorati.com/tags/nmalovic" rel="tag"&gt;nmalovic&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=624" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=fuedrrgXicc:-bxxrHJWnjk:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=fuedrrgXicc:-bxxrHJWnjk:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=fuedrrgXicc:-bxxrHJWnjk:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=fuedrrgXicc:-bxxrHJWnjk:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/fuedrrgXicc" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Test+Driven+Development/default.aspx">Test Driven Development</category><category domain="http://blog.vuscode.com/malovicn/archive/tags/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/04/17/prism-cal-unit-testing-how-to-test-prism-cal-event-aggregator-using-rhino-mocks.aspx</feedburner:origLink></item><item><title>Microsoft Unity Auto Mocking Container?</title><link>http://feedproxy.google.com/~r/vuscode/~3/2izNDPQnMCY/microsoft-unity-auto-mocking-container.aspx</link><pubDate>Sat, 04 Apr 2009 13:07:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:617</guid><dc:creator>malovicn</dc:creator><slash:comments>2</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=617</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/04/04/microsoft-unity-auto-mocking-container.aspx#comments</comments><description>&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;How to build Microsoft Unity Auto Mocking container in less then 20 minutes of work…&lt;/h1&gt;
&lt;p&gt;I have written before in detail about &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/08/design-for-testability-auto-mocking-container-amc-part-9.aspx" target="_blank"&gt;Auto Mocking Containers&lt;/a&gt; so I’ll skip here details on what is it etc and jump to the main point of this post: implementation of auto mocking container for Microsoft Unity.&lt;/p&gt;
&lt;p&gt;Faced with PIA caused by constant explicit mocking of constructor dependencies (some of them not even used in my tests), I’ve tried to Google my way out by searching for Unity AMC on Codeplex, Google code etc. To my surprise that didn’t went well with best match being &lt;a title="http://weblogs.asp.net/rosherove/archive/2008/04/14/creating-a-automockingcontainer-with-microsoft-unity-pretty-darn-simple.aspx" href="http://weblogs.asp.net/rosherove/archive/2008/04/14/creating-a-automockingcontainer-with-microsoft-unity-pretty-darn-simple.aspx" target="_blank"&gt;Roy Osherove Unity AMC container blog post&lt;/a&gt; which is just a nice fluent interface allowing explicit mock creation and injection on easier way. In other words, nothing automatic happening there at least not in a sense I needed it for my tests.&lt;/p&gt;
&lt;p&gt;I started looking for the Object builder documentation and found some for version one scattered on couple of sites. The only thing I get from that documentation was that ObjectBuilder is one complex thing and “patching it” was far away from my end design goal: quick solution.&lt;/p&gt;
&lt;p&gt;So, once I realized that I can not solve this on ninja way I tried “brute force” approach and in 20 minutes I had working Unity AMC. &lt;/p&gt;
&lt;p&gt;The idea is simple: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;create a class specializing the UnityContainer - “AutoMockingUnityContainer” &lt;/li&gt;
&lt;li&gt;override UnityContainer “Get” methods &lt;/li&gt;
&lt;li&gt;wrap in try catch block every “Resolve” call&lt;/li&gt;
&lt;li&gt;if ResolutionFailedException would occur using reflection find greediest constructor (with the most parameters) &lt;/li&gt;
&lt;li&gt;if no constructor info available, return a mock &lt;/li&gt;
&lt;li&gt;try to resolve those parameters by using AMC resolve method &lt;/li&gt;
&lt;li&gt;recourse until you won’t have complete set of arguments needed (real or mocked instances) for constructing the originally requested instance &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;Code explaining the above mentioned concepts is even simpler so let cut the chase and&amp;nbsp; save you from pain caused by reading more text written with “my English” ..&lt;/p&gt;
&lt;h2&gt;&lt;/h2&gt;
&lt;h1&gt;&lt;/h1&gt;
&lt;h2&gt;“Show me the code”&lt;/h2&gt;
&lt;p&gt;Imagine we would have a console application which is giving the answer on the meaning of the life&lt;/p&gt;&lt;pre class="c-sharp"&gt;using System;
using Microsoft.Practices.Unity;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            var user = container.Resolve&amp;lt;User&amp;gt;();
            Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
            Console.ReadKey();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(Code creates UnityContainer instance and the uses it to retrieve instance of user class which WhatIsTheMeaningOfTheLife method is then shown in console output.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;User&lt;/strong&gt; class is implemented like this:&lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace ConsoleApplication1
{
    public class User
    {
        private readonly ICompanyManager companyManager;

        public User(ICompanyManager companyManager)
        {
            this.companyManager = companyManager;
        }

        public int WhatIsTheMeaningOfTheLife()
        {
            return 42;
        }
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;(User class constructor accepts ICompanyManager parameter which BTW is totally not used in the method used in console application.)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Although totally irrelevant for this blog post, here’s &lt;strong&gt;ICompanyManger &lt;/strong&gt;class code (just not to have any secrets :)):&lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace ConsoleApplication1
{
    public interface ICompanyManager
    {
        void NotImportantMethod();
    }
}&lt;/pre&gt;
&lt;p&gt;If I would run this code as it is I would be rewarded by the nice Unity &lt;strong&gt;ResolutionFailedException&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;&lt;em&gt;Resolution of the dependency failed, type = &amp;quot;ConsoleApplication1.User&amp;quot;, name = &amp;quot;&amp;quot;. Exception message is: The current build operation (build key Build Key[ConsoleApplication1.User, null]) failed: The parameter companyManager could not be resolved when attempting to call constructor ConsoleApplication1.User(ConsoleApplication1.ICompanyManager companyManager). (Strategy type BuildPlanStrategy, index 3)&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Reason is pretty obvious: Unity container didn’t have any mapping defined for ICompanyManager which is required in order for user class to be required.&lt;/p&gt;
&lt;h2&gt;AutoMockingUnityContainer&lt;/h2&gt;
&lt;p&gt;Is just a class looking like this&lt;/p&gt;&lt;pre class="c-sharp"&gt;using System.Diagnostics;
using Microsoft.Practices.Unity;

namespace UnityAMC
{
    public class AutoMockingUnityContainer  : UnityContainer
    {
        private readonly MockingHelper mockingHelper;

        public AutoMockingUnityContainer()
        {
             mockingHelper = new MockingHelper(this);
        }
        
        public override object Resolve(System.Type t, string name)
        {
            try
            {
                return base.Resolve(t, name); 
            }
            catch (ResolutionFailedException)
            {
                Debug.WriteLine(string.Format(&amp;quot;Conflict resolution of type:{0}&amp;quot;, t));
                return mockingHelper.ConstructInstance(t);
            }
            
        }
    }
}&lt;/pre&gt;
&lt;p&gt;As you can see no magic there and it does exactly what everyone would expect:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Inherit the UnityContainer &lt;/li&gt;
&lt;li&gt;Override the Resolve method &lt;/li&gt;
&lt;li&gt;Adds to that override Try Catch block which in case of ResolutionFailedException exception calls the mockingHelper ConstructInstance method &lt;/li&gt;
&lt;li&gt;Mocking helper instance is stored in a field and constructed with pointer to current unity container in AMCContainer constructor &lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;MockingHelper class&lt;/h3&gt;
&lt;p&gt;Is just 90 line long class looking like this:&lt;/p&gt;&lt;pre class="c-sharp"&gt;using System;
using System.Diagnostics;
using System.Reflection;
using Microsoft.Practices.Unity;
using Rhino.Mocks;

namespace UnityAMC
{
    public class MockingHelper
    {
        private readonly IUnityContainer unityContainer;
        readonly MockRepository mockRepository = new MockRepository();
        private const string DebugCategory = &amp;quot;UnityAMC.MockingHelper&amp;quot;;

        public MockingHelper(IUnityContainer unityContainer)
        {
            this.unityContainer = unityContainer;
        }

        #region Helper methods
        /// 
        /// Construct the instance.
        /// 
        /// The type which is to be constructed.
        /// An instance of service type.
        public object ConstructInstance(Type serviceType)
        {
            ConstructorInfo constructorInfo;
            try
            {
                constructorInfo = GetGreediestConstructor(serviceType.GetConstructors());
            }
            catch (Exception)
            {
                try
                {
                    Debug.WriteLine(string.Format(&amp;quot;Mock created - {0}&amp;quot;, serviceType), DebugCategory);

                    // returning mock of service not added to container
                    return this.mockRepository.DynamicMock(serviceType, new object[0]);
                }
                catch (Exception ex2)
                {
                    return new AutoMockingContainerContainerResolutionException(string.Format(&amp;quot;Auto mocking failed for type:{0}&amp;quot;, serviceType), ex2);
                }
            }

            var constructorParameters = constructorInfo.GetParameters();
            var arguments = new object[constructorParameters.Length];

            var counter = 0;
            foreach (var parameterInfo in constructorParameters)
            {
                arguments[counter++] = this.unityContainer.Resolve(parameterInfo.ParameterType, string.Empty);
            }

            return constructorInfo.Invoke(arguments);
        }

        /// 
        /// Gets the greediest constructor.
        /// 
        /// The constructor infos.
        /// Greediest constructor.
        private static ConstructorInfo GetGreediestConstructor(ConstructorInfo[] constructorInfos)
        {
            if (constructorInfos.Length == 0)
            {
                throw new InvalidOperationException(&amp;quot;No available constructors.&amp;quot;);
            }

            if (constructorInfos.Length == 1)
            {
                return constructorInfos[0];
            }

            var result = constructorInfos[0];
            for (int i = 1; i &amp;lt; constructorInfos.Length; i++)
            {
                if (constructorInfos[i].GetParameters().Length &amp;gt; result.GetParameters().Length)
                {
                    result = constructorInfos[i];
                }
            }

            return result;
        }
        #endregion
    }
}&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;GetGreediestConstructor&lt;/strong&gt; method purpose is to get from a given collection of type constructor info&amp;#39;s the one which has the most arguments.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;ConstructInstanceMethod&lt;/strong&gt; does next things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;For a given type tries to get greediest constructor 
&lt;ul&gt;
&lt;li&gt;If no constructor available on a given type&amp;nbsp; (ex. in case of interface) it returns dynamic mock. &lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;code then iterates through the greediest constructor parameters and tries to resolve each one of them &lt;/li&gt;
&lt;li&gt;if resolution of any of them fails the procedure goes again just this time ConstructInstanceMethod would go one level deeper in object graph. &lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;And that’s about it…&lt;/p&gt;
&lt;p&gt;If I would modify my console app code to use AutoMockingUnityContainer instead of UnityContainer, I would end with code looking like this&lt;/p&gt;&lt;pre&gt;using System;
using Microsoft.Practices.Unity;
using UnityAMC;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new &lt;strong&gt;&lt;font color="#ff0000"&gt;AutoMockingUnityContainer&lt;/font&gt;&lt;/strong&gt;();
            var user = container.Resolve&amp;lt;User&amp;gt;();
            Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
            Console.ReadKey();
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Which would run just fine…&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_2298217B.png"&gt;&lt;img title="image" style="BORDER-RIGHT:0px;BORDER-TOP:0px;DISPLAY:inline;BORDER-LEFT:0px;BORDER-BOTTOM:0px;" height="72" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_23BC6EC0.png" width="678" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Although I found this way of doing Unity AMC pretty naive and dumb, it works perfectly in my test fixtures for couple of months already with 20 minutes spent on making it. If anyone do this on ninja way, I would be more then happy to start using that but in the meantime … :)&lt;/p&gt;
&lt;p&gt;My little code example can be downloaded from &lt;a href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/AMC.zip" target="_blank"&gt;here&lt;/a&gt;&lt;/p&gt;
&lt;div class="wlWriterEditableSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:ac164a7b-cfa7-45c3-9b2a-15917ebd4ef7" style="PADDING-RIGHT:0px;DISPLAY:inline;PADDING-LEFT:0px;FLOAT:none;PADDING-BOTTOM:0px;MARGIN:0px;PADDING-TOP:0px;"&gt;Technorati Ознаке: &lt;a href="http://technorati.com/tags/Unity" rel="tag"&gt;Unity&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Mocking" rel="tag"&gt;Mocking&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rhino" rel="tag"&gt;Rhino&lt;/a&gt;,&lt;a href="http://technorati.com/tags/AutoMockingContainer" rel="tag"&gt;AutoMockingContainer&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=617" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=2izNDPQnMCY:LlR9eRiIyIM:yIl2AUoC8zA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=2izNDPQnMCY:LlR9eRiIyIM:7Q72WNTAKBA"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?d=7Q72WNTAKBA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~ff/vuscode?a=2izNDPQnMCY:LlR9eRiIyIM:F7zBnMyn0Lo"&gt;&lt;img src="http://feeds.feedburner.com/~ff/vuscode?i=2izNDPQnMCY:LlR9eRiIyIM:F7zBnMyn0Lo" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/2izNDPQnMCY" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Test+Driven+Development/default.aspx">Test Driven Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/04/04/microsoft-unity-auto-mocking-container.aspx</feedburner:origLink></item><item><title>Fluent NHibernate – Convention over configuration – AutoPersistenceModel auto map magic</title><link>http://feedproxy.google.com/~r/vuscode/~3/47kfcF4JBq8/fluent-nhibernate-nhibernate-without-configuration-files-automap-magic.aspx</link><pubDate>Sat, 03 Jan 2009 14:58:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:575</guid><dc:creator>malovicn</dc:creator><slash:comments>7</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=575</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2009/01/03/fluent-nhibernate-nhibernate-without-configuration-files-automap-magic.aspx#comments</comments><description>&lt;h1&gt;&lt;/h1&gt;
&lt;h1&gt;Story about how fluent nhibernate idea was born&lt;/h1&gt;
&lt;p&gt;&lt;strong&gt;POST UPDATE: Due to changes in Auto mapping API this blog post is outdated. In order to see auto mapping in action with FNH 1.0 go check out &lt;/strong&gt;&lt;a href="http://blog.vuscode.com/malovicn/archive/2009/11/04/fluent-nhibernate-samples-auto-mapping-part-1-2.aspx"&gt;&lt;strong&gt;http://blog.vuscode.com/malovicn/archive/2009/11/04/fluent-nhibernate-samples-auto-mapping-part-1-2.aspx&lt;/strong&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;*******************************************************************************************************&lt;/p&gt;
&lt;p&gt;Fluent NHibernate is an open source project (&lt;a href="http://fluent-nhibernate.googlecode.com/svn/trunk/" target="_blank"&gt;fluent NHibernate trunk&lt;/a&gt;&lt;strong&gt;&lt;/strong&gt;) which implements &lt;a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank"&gt;fluent interface&lt;/a&gt; on top of the &lt;a href="http://en.wikipedia.org/wiki/NHibernate" target="_blank"&gt;NHibernate ORM&lt;/a&gt; configuration capabilities which are based on xml configuration files (as most of the Java ports are) where every entity is defined in it’s own configuration file. &lt;/p&gt;
&lt;p&gt;The main reason behind existence of the Fluent NHibernate project is that working with those configuration files is not something very productive and (in general) it is one of the major turning off points for developers trying to get NHibernate.&lt;/p&gt;
&lt;p&gt;As I mentioned in my &lt;a title="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" href="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" target="_blank"&gt;Using NHibernate without configuration files&lt;/a&gt; post, it is possible to replace the act of creation of configuration files with the c# code where instead of every configuration file defining entities we would have separate mapping class.&amp;nbsp; That functionality per se is awesome improvement comparing to configuration files, but it is still cumbersome work requiring a lot of repetitive work. &lt;/p&gt;
&lt;p&gt;Here are couple of illustration of what kind of repentance I have on my mind with previous sentence:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;My tables are having the same name as my entities (just in plural form) &lt;/li&gt;
&lt;li&gt;I could have 50 entity classes where every identity property would be called ID and in database I would always have primary key consisting of “table name + ID” &lt;/li&gt;
&lt;li&gt;Data table foreign key can be always defined following the naming rule of “parent table name + ID” &lt;/li&gt;
&lt;li&gt;Most of my text based columns have 255 length characters &lt;/li&gt;
&lt;li&gt;etc &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;Those rules are changing but each one of us (personally or on organization level) has a certain style of doing this things, predefined code and database standards on organization level or just agreement on team level. Based on that fact of &lt;u&gt;&lt;strong&gt;convention &lt;/strong&gt;&lt;/u&gt;existence, &lt;a href="http://ayende.com/Blog/Default.aspx" target="_blank"&gt;The Don Ayende&lt;/a&gt;&amp;nbsp;&lt;a href="http://www.ayende.com/Blog/archive/2008/08/12/On-Fluent-NHibernate.aspx" target="_blank"&gt;asked for some magic to be added to Fluent NHibernate&lt;/a&gt;. His point was that he would like to be able to describe easily what the conventions (similar to the one I’ve enlisted above) are used in ORM area of the project and then based on those conventions fluent NHibernate should generate all of the configuration files &lt;strong&gt;automatically&lt;/strong&gt;. Once those default configuration files state&amp;nbsp; would be achieved, the developer would then modify configuration mappings to cover only the cases being an exception from the conventions.&lt;/p&gt;
&lt;p&gt;Brilliant minds behind Fluent NHibernate &lt;a href="http://groups.google.com/group/fluent-nhibernate/browse_thread/thread/5d7a524fb6ffcae/db03acb06e8210b2?lnk=gst&amp;amp;q=Ayende#db03acb06e8210b2" target="_blank"&gt;get their heads together&lt;/a&gt; and implemented that AutoMap functionality Ayende was asking and I was recently playing with it and want to share my experiences with the community.&lt;/p&gt;
&lt;p&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;(Source code of the example used in this blog post can be found &lt;/strong&gt;&lt;/font&gt;&lt;a title="source code" href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/AutoMapNHibernate.zip" target="_blank"&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;here&lt;/strong&gt;&lt;/font&gt;&lt;/a&gt;&lt;font color="#ff0000"&gt;&lt;strong&gt;)&lt;/strong&gt;&lt;/font&gt;&lt;/p&gt;
&lt;h2&gt;Blog post set up&lt;/h2&gt;
&lt;p&gt;I’ll use the same example as the one I’ve used in&amp;nbsp; &lt;a title="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" href="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" target="_blank"&gt;Using NHibernate without configuration files&lt;/a&gt; post. The good side of that decision is that you would be able to see same example done on both (manual and auto map) ways but on the flip side (to understand in detail what is the use case scenario etc) you would have to read the original post because here I would just summarize it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Class diagram&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_0F4446F0.png"&gt;&lt;img style="DISPLAY:inline;" title="image" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_1C0E7741.png" width="640" height="370" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;SQL Database model&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_24CE59C0.png"&gt;&lt;img style="DISPLAY:inline;" title="image" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5D0CD0D8.png" width="511" height="217" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Couple of major points to be noted here:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Customer has an address (Customer.CustomerAddress property) and a collection of reference people handling his requests (References property) &lt;/li&gt;
&lt;li&gt;SQL Data model has two tables while class diagram has 3 classes. The difference is that Address class data on database level is embedded into customer table. In NHibernate parlance, that is called component. &lt;/li&gt;
&lt;li&gt;Class diagrams all have their identity property named “ID” while database primary key columns are named following the “table name + ID” rule. &lt;/li&gt;
&lt;li&gt;Database table names are plural form of class entities. (Customer –&amp;gt; Customers, ReferencePerson –&amp;gt; ReferencePeople) &lt;/li&gt;
&lt;li&gt;ReferencePerson class has property named LastName while ReferencePeople table has column named SurName &lt;/li&gt;
&lt;li&gt;All of the entities implement IEntity which is totally not necessary for this example and\or your code but is something so commonly used that most of the examples on the web contain base entity class or interface. That’s why I added IEntity to this example to illustrate how AutoMap works in that use case too &lt;/li&gt;&lt;/ul&gt;
&lt;h2&gt;Project structure&lt;/h2&gt;
&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_036EB424.png"&gt;&lt;img style="MARGIN:0px 20px 0px 0px;DISPLAY:inline;" title="image" alt="image" align="left" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_094957BD.png" width="130" height="240" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;p&gt;&lt;br /&gt;The project structure of the solution used in this example looks like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;BusinessLayer &lt;/strong&gt;project contains entities presented in calss diagram without referencing infrastructure (PI\POCO design criteria) &lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;br /&gt;NHibernateInfrastructure &lt;/strong&gt;project contains two files: 
&lt;ul&gt;
&lt;li&gt;Inflector – this class is “borrowed” from &lt;a href="https://svn.castleproject.org/svn/castle/trunk/ActiveRecord/Castle.ActiveRecord/Framework/Internal/Inflector.cs" target="_blank"&gt;Active Record code base&lt;/a&gt; and it sole purpose is to pluralize entity names to database table names &lt;/li&gt;
&lt;li&gt;NHibernateBootstrapper.cs is a class which performs complete initialization of NHibernate engine based on auto map and manual definitions and result with NHibernate session being created at the end of build up process. Most of this blog post would be related to this class &lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;NHibernateInfrastructure.Test project contains test fixture (MappingTest) similar to the one from the manual map post. &lt;/li&gt;&lt;/ul&gt;
&lt;blockquote&gt;&lt;/blockquote&gt;
&lt;h2&gt;An example of Fluent NHibernate auto mapping functionality&lt;/h2&gt;
&lt;h3&gt;&lt;/h3&gt;
&lt;h3&gt;Before I start&lt;/h3&gt;
&lt;p&gt;Unfortunately there are no official documents presenting “the right way” to do this auto mapping. Most of the examples on net are covering same trivial example and they are not very helpful too. (Btw, lack of documentation was the reason behind writing this blog post) .I am by no mean expert in fluent NHibernate so while the code presented in this blog post is fully functional there might be some better ways how to do some of the presented functionality. In other words, take the example code bellow more as a starting point and spend some time with Fluent NHibernate examining it. It would be very worth spent time, I can promise you that.&lt;/p&gt;
&lt;p&gt;Now the disclaimer is done, let’s roll :)&lt;/p&gt;
&lt;h3&gt;High level overview &lt;/h3&gt;
&lt;p&gt;Here’s the content of NHibernateBootstrapper.cs class (warning: significant amount of code coming but worth of reading I hope :) )&lt;/p&gt;&lt;pre class="c-sharp"&gt;        
public ISessionFactory InitSessionFactory()
        {
            var config =
                    MsSqlConfiguration.MsSql2005
                    .ConnectionString.Is(
                        @&amp;quot;Data Source=.\SQL2008;Initial Catalog=NHibernateBlog;&amp;quot; 
                        + @&amp;quot;Integrated Security=True&amp;quot;)
                    .UseReflectionOptimizer()
                    .ConfigureProperties(new Configuration());

            // 1. defining conventions and scope of the auto persistence model
            var autoPersistenceModel = GetPersistenceModelFromAutoMapping();
            
            // 2. defining exclusions form auto persistence 
            UpdatePersistenceModelWithExclusions(autoPersistenceModel);

            // 3. overriding auto mapping defaults
            UpdatePersistenceModelWithManualMappingInformations(autoPersistenceModel);

            // 4. writing auto mapping definitions (needed just for blog post) 
            autoPersistenceModel.WriteMappingsTo(@&amp;quot;C:\Temp&amp;quot;);
            
            // 5. Configuring NHibernate configuration using auto persistence model
            autoPersistenceModel.Configure(config);

            // returning session factory from given configuration
            return config.BuildSessionFactory();
        }	&lt;/pre&gt;
&lt;p&gt;InitSessionFactory is the the only public method which is called from application assembly and which task is to return session factory created based on defined mapping informations. &lt;/p&gt;
&lt;p&gt;Beginning of the method is related to creating Sql 2005 standard configuration (NHibernateBlog DB backup file is given in zip file accompanying this blog post)&lt;/p&gt;
&lt;p&gt;Then the method perform 5 step configuration initialization:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Create AutoPersistanceModel containing all the default mapping rules regarding how and what to auto map. &lt;/li&gt;
&lt;li&gt;Define domain elements which are to be excluded from the auto mapping persistence model definition due to the fact that they don’t fit to defined conventions &lt;/li&gt;
&lt;li&gt;Define all of the manual mapping information fore domain elements which are not auto mapped &lt;/li&gt;
&lt;li&gt;Write mappings xml configuration files to hard drive (not needed in production, just for you to check out the result of the fluent NHibernate auto mapping routine) &lt;/li&gt;
&lt;li&gt;Configure NHibernate configuration with AutoPeristenceModel initialized in steps #1 - #3 &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;Once NHibernate is configured session factory is built and returned for further consumption.&lt;/p&gt;
&lt;p&gt;Now when we saw high level steps, let check out how those steps look in more detail..&lt;/p&gt;
&lt;h2&gt;&lt;/h2&gt;
&lt;h3&gt;Creating of AutoPersistenceModel &lt;/h3&gt;
&lt;p&gt;Let see what is inside of the GetPerisicatnceModelFromAutoMapping method &lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace NHConfigMappings
{
   ...
       private static AutoPersistenceModel GetPersistenceModelFromAutoMapping()
        {
            return AutoPersistenceModel.MapEntitiesFromAssemblyOf&amp;lt;Customer&amp;gt;()
                    
                    // defining what is to be auto mapped
                    .Where(type =&amp;gt;
                                    typeof(IEntity).IsAssignableFrom(type) 
                                    &amp;amp;&amp;amp; type.IsClass 
                                    &amp;amp;&amp;amp; !type.IsAbstract
                                    &amp;amp;&amp;amp; type.Namespace == &amp;quot;CustomerConfiguration&amp;quot;)
                    
                    // defining convention attributes
                    .WithConvention(convention =&amp;gt;
                    {
                        convention.FindIdentity = p =&amp;gt; p.Name == &amp;quot;ID&amp;quot;;
                        convention.GetTableName = type =&amp;gt; Inflector.Pluralize(type.Name);
                        convention.GetPrimaryKeyNameFromType = type =&amp;gt; type.Name + &amp;quot;ID&amp;quot;;
                        convention.GetForeignKeyNameOfParent = p =&amp;gt; p.Name + &amp;quot;ID&amp;quot;;
                        convention.DefaultStringLength = 50;
                        convention.OneToManyConvention = o =&amp;gt; o.Cascade.All();
                    });
        }
   ...	
}	&lt;/pre&gt;
&lt;p&gt;AutoPersistenceMode has a static factory method MapEntitiesFromAssemblyOf&amp;lt;T&amp;gt; where T is a type defined in a assembly containing entities which are about to be auto mapped. Very cool way for providing assembly name information. In the case of this blog post, Customer type is defined in BusinessLayer asembly, so this line would provide that information to fluent nhibernate auto mapping logic.&lt;/p&gt;
&lt;p&gt;Then there’s a Where method which purpose is to define what types of a given assembly are to be mapped. In a sense it defines filter constraint criteria for auto mapping logic. In the case of this blog post, filter criteria is set to something like “all non abstract types implementing the IEntity which are defined in CustomerConfiguration namespace” . Any type not matching those rules wouldn’t be included in auto mapping process.&lt;/p&gt;
&lt;p&gt;Once I’ve defined “what”, I start defining “how” by defining auto mapping conventions which are set of general settings defining how auto mapping logic should behave.&lt;/p&gt;
&lt;p&gt;In the case of this blog post, conventions are defined like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Every class would have identity property with name “ID” (If your property would be named “Id” there won’t be need for explicit definition because that is default setting Fluent Nhibernate uses) &lt;/li&gt;
&lt;li&gt;Database table name should be plural form of the class entity name (example: class Customer –&amp;gt; table Customers) &lt;/li&gt;
&lt;li&gt;Primary key&amp;nbsp; column name&amp;nbsp; would consist of type name and “ID” suffix&amp;nbsp; (example: PK of Customer table would be named CustomerID) &lt;/li&gt;
&lt;li&gt;Foreign key column name would consist of parent type name and ID suffix&amp;nbsp;&amp;nbsp; (example: FK of ReferencePeople table would be CustomerID) &lt;/li&gt;
&lt;li&gt;Every string class property would be by default mapped to 50 character length column &lt;/li&gt;
&lt;li&gt;Every One – To – Many mapping would have Cascade.All cascade setting by default &lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;&lt;/h3&gt;
&lt;h3&gt;Defining exclusions from AutoPersistenceModel definition&lt;/h3&gt;
&lt;p&gt;Now when I defined default mapping rules, I need to define what needs to be excluded from that auto mapping&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace NHConfigMappings
{
        private static void UpdatePersistenceModelWithExclusions(AutoPersistenceModel persistenceModel)
        {
            persistenceModel
                    .ForTypesThatDeriveFrom&amp;lt;Customer&amp;gt;(c =&amp;gt; c.IgnoreProperty(p =&amp;gt; p.CustomerAddress))
                    .ForTypesThatDeriveFrom&amp;lt;ReferencePerson&amp;gt;(c =&amp;gt; c.IgnoreProperty(p =&amp;gt; p.LastName));
        }
   ...	
}	&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;As we can see here I’ve defined next exclusions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cutomer.CustomerAddress property shouldn’t be auto mapped (because that would be Component and not One-To-Many type of mapping) &lt;/li&gt;
&lt;li&gt;ReferencePerson.LastName&amp;nbsp; property shouldn’t be auto mapped (LastName property wouldn’t be mapped to LastName column) &lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;Adding manual mapping definition to AutoPersistenceModel&lt;/h3&gt;
&lt;p&gt;For all of the non mapped and excluded exceptional entities which we still need to map to database entities, Fluent Nhibernate defines&amp;nbsp; a way of adding manual mapping definitions to auto map defined auto persistence model &lt;br /&gt;&lt;/p&gt;
&lt;p&gt;Here’s the code sample:&lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace NHConfigMappings
{
   ...
        private static void UpdatePersistenceModelWithManualMappingInformations(AutoPersistenceModel persistenceModel)
        {
            // adding manual mapping to auto mapped persistence model 
            // 1. column level exceptions
            persistenceModel.FindMapping&amp;lt;ReferencePerson&amp;gt;().Map(p =&amp;gt; p.LastName, &amp;quot;SurName&amp;quot;);

            // 2. components definition
            persistenceModel.FindMapping&amp;lt;Customer&amp;gt;()
		.Component&amp;lt;Address&amp;gt;            (
                    x =&amp;gt; x.CustomerAddress,
                    m =&amp;gt;
                    {
                        m.Map(x =&amp;gt; x.Street).WithLengthOf(100);
                        m.Map(x =&amp;gt; x.PostalCode).WithLengthOf(6);
                        m.Map(x =&amp;gt; x.Town).WithLengthOf(30);
                        m.Map(x =&amp;gt; x.Country).WithLengthOf(50);
                    });
        }
   ...	
}	
&lt;address&gt;&lt;/address&gt;&lt;/pre&gt;
&lt;p&gt;UpdatePersistenceModelWithManualMappingInformations method updates persistance model like this:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In auto persistence model definition find mapping for ReferencePerson entity and add mapping of the LastName property (to be mapped to SurName property) &lt;/li&gt;
&lt;li&gt;In auto persistence model definition find mapping for Customer entity and add component mapping for CustomerAddress property as defined in code sample &lt;/li&gt;&lt;/ul&gt;
&lt;h3&gt;&lt;/h3&gt;
&lt;h3&gt;Checking the xml configuration files&lt;/h3&gt;
&lt;p&gt;Let’s take a quick peek at how configuration files generated from AutoPersistenceModel would look like&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CustomerConfiguration.Customer.xml&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="xml"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;hibernate-mapping xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot; default-lazy=&amp;quot;true&amp;quot; assembly=&amp;quot;CustomerConfiguration&amp;quot; namespace=&amp;quot;CustomerConfiguration&amp;quot;&amp;gt;
  &amp;lt;class name=&amp;quot;ReferencePerson&amp;quot; table=&amp;quot;ReferencePeople&amp;quot; xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot;&amp;gt;
    &amp;lt;id name=&amp;quot;ID&amp;quot; column=&amp;quot;ReferencePersonID&amp;quot; type=&amp;quot;Guid&amp;quot;&amp;gt;
      &amp;lt;generator class=&amp;quot;guid.comb&amp;quot; /&amp;gt;
    &amp;lt;/id&amp;gt;
    &amp;lt;property name=&amp;quot;LastName&amp;quot; column=&amp;quot;Surname&amp;quot; length=&amp;quot;50&amp;quot; type=&amp;quot;String&amp;quot;&amp;gt;
      &amp;lt;column name=&amp;quot;Surname&amp;quot; /&amp;gt;
    &amp;lt;/property&amp;gt;
    &amp;lt;property name=&amp;quot;FirstName&amp;quot; column=&amp;quot;FirstName&amp;quot; length=&amp;quot;50&amp;quot; type=&amp;quot;String&amp;quot;&amp;gt;
      &amp;lt;column name=&amp;quot;FirstName&amp;quot; /&amp;gt;
    &amp;lt;/property&amp;gt;
  &amp;lt;/class&amp;gt;
&amp;lt;/hibernate-mapping&amp;gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;CustomerConfiguration.ReferencePerson.xml&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;pre class="xml"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;hibernate-mapping namespace=&amp;quot;CustomerConfiguration&amp;quot; assembly=&amp;quot;CustomerConfiguration&amp;quot; default-lazy=&amp;quot;true&amp;quot; xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot;&amp;gt;
  &amp;lt;class name=&amp;quot;ReferencePerson&amp;quot; xmlns=&amp;quot;urn:nhibernate-mapping-2.2&amp;quot; table=&amp;quot;ReferencePeople&amp;quot;&amp;gt;
    &amp;lt;property name=&amp;quot;LastName&amp;quot; type=&amp;quot;String&amp;quot; length=&amp;quot;50&amp;quot; column=&amp;quot;Surname&amp;quot;&amp;gt;
      &amp;lt;column name=&amp;quot;Surname&amp;quot; /&amp;gt;
    &amp;lt;/property&amp;gt;
  &amp;lt;/class&amp;gt;
&amp;lt;/hibernate-mapping&amp;gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now imagine you have hundreds of tables and entities and think about how much time and effort Fluent Nhibernate auto mapping functionality saves. Neat isn’t it?&lt;/p&gt;
&lt;h2&gt;Testing the AutoPersistenceModel based auto mappings&lt;/h2&gt;
&lt;p&gt;For the end of the blog post there’s only one thing left and that is to run the same test I wrote for &lt;a title="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" href="http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx" target="_blank"&gt;Using NHibernate without configuration files&lt;/a&gt; post and to show that auto mapping works like it was working with manual class map definition&lt;/p&gt;
&lt;p&gt;Here’s test fixture code…&lt;/p&gt;&lt;pre class="c-sharp"&gt;namespace NHConfigMappings.Test
{
    using System.Collections.Generic;
    using CustomerConfiguration;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
   using NHibernate;

    [TestClass]
    public class MappingsTest
    {
        private static ISessionFactory _sessionFactory;

        [ClassInitialize]
        public static void FixtureInit(TestContext testContext)
        {
            _sessionFactory = new NHibernateBootstrapper().InitSessionFactory();
        }

        [TestMethod]
        public void ReferencePerson_Create_ShouldCreateRowInDb()
        {
            var customer = new Customer
               {
                   Name = &amp;quot;John Doe&amp;quot;,
                   CustomerNumber = &amp;quot;12345&amp;quot;,
                   CustomerAddress = new Address
                                         {
                                             Street = &amp;quot;1st Mayson Street&amp;quot;,
                                             PostalCode = &amp;quot;01754&amp;quot;,
                                             Town = &amp;quot;Maynard&amp;quot;,
                                             Country = &amp;quot;USA&amp;quot;
                                         },
                   References = new List
                                          {
                                              new ReferencePerson
                                                  {
                                                      FirstName = &amp;quot;Nikola&amp;quot;,
                                                      LastName = &amp;quot;Malovic&amp;quot;
                                                  }
                                          }
               };

            ISession session = _sessionFactory.OpenSession();
            session.Save(customer);
            session.Flush();

            session.Evict(customer);
            
            var customerDB= session.Get&amp;lt;Customer&amp;gt;(customer.ID);
            Assert.IsTrue(  customerDB.ID == customer.ID &amp;amp;&amp;amp; customerDB.Name == customer.Name 
                            &amp;amp;&amp;amp; customerDB.CustomerAddress.Street == &amp;quot;1st Mayson Street&amp;quot;
                            &amp;amp;&amp;amp; customerDB.References[0].FirstName == &amp;quot;Nikola&amp;quot;);

        }
    }
}&lt;/pre&gt;
&lt;p&gt;The main difference between tests in previous blog post and this one is that we don’t have in fixture init explicit session factory initialization. Instead, there’s only call to NHIbernateBootstrapper class InitSessionFactory method which I’ve already presented in this blog post. Test method is completely the same as the one from previous post. So it is the result of test run&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/image_52F82FAD.png"&gt;&lt;img style="DISPLAY:inline;" title="image" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_6638E64C.png" width="640" height="75" /&gt;&lt;/a&gt; &lt;/p&gt;
&lt;h2&gt;&lt;/h2&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h1&gt;Conclusions&lt;/h1&gt;
&lt;ol&gt;
&lt;li&gt;NHIbernate rock! &lt;/li&gt;
&lt;li&gt;Fluent NHibernate Auto mapping functionality rock! &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;There are a lot of blog posts about auto mapping functionality you might want to check out:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a title="http://ayende.com/Blog/archive/2008/12/11/fluent-nhibernate.aspx" href="http://ayende.com/Blog/archive/2008/12/11/fluent-nhibernate.aspx"&gt;http://ayende.com/Blog/archive/2008/12/11/fluent-nhibernate.aspx&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a title="http://www.chrisvandesteeg.nl/2008/12/02/fluent-nhibernates-autopersistencemodel-i-love-it/" href="http://www.chrisvandesteeg.nl/2008/12/02/fluent-nhibernates-autopersistencemodel-i-love-it/"&gt;http://www.chrisvandesteeg.nl/2008/12/02/fluent-nhibernates-autopersistencemodel-i-love-it/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a title="http://www.pnpguidance.net/Post/AutoPersistenceModelFluentNHibernateORMapper.aspx" href="http://www.pnpguidance.net/Post/AutoPersistenceModelFluentNHibernateORMapper.aspx"&gt;http://www.pnpguidance.net/Post/AutoPersistenceModelFluentNHibernateORMapper.aspx&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a title="http://marekblotny.blogspot.com/2008/12/fluent-nhibernate-conventions-and.html" href="http://marekblotny.blogspot.com/2008/12/fluent-nhibernate-conventions-and.html"&gt;http://marekblotny.blogspot.com/2008/12/fluent-nhibernate-conventions-and.html&lt;/a&gt; &lt;/li&gt;&lt;/ul&gt;
&lt;div style="PADDING-BOTTOM:0px;MARGIN:0px;PADDING-LEFT:0px;PADDING-RIGHT:0px;DISPLAY:inline;FLOAT:none;PADDING-TOP:0px;" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:47cff7c6-7bc1-4aa6-adb5-3e18f27576a7" class="wlWriterSmartContent"&gt;Technorati Oznake: &lt;a href="http://technorati.com/tags/NHibernate" rel="tag"&gt;NHibernate&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Fluent+NHibernate" rel="tag"&gt;Fluent NHibernate&lt;/a&gt;,&lt;a href="http://technorati.com/tags/ORM" rel="tag"&gt;ORM&lt;/a&gt;,&lt;a href="http://technorati.com/tags/nmalovic" rel="tag"&gt;nmalovic&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=575" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=TYvT0uGj"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?d=41" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/vuscode?a=Bpp0tUSa"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?d=50" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="http://feeds.feedburner.com/~f/vuscode?a=HxAEhsfM"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=HxAEhsfM" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/47kfcF4JBq8" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2009/01/03/fluent-nhibernate-nhibernate-without-configuration-files-automap-magic.aspx</feedburner:origLink></item></channel></rss>
