<?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>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>3</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:56 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;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;#160; 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;#160;&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;#160; 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;#160; &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 title="image" style="display:inline;" height="370" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_1C0E7741.png" width="640" /&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 title="image" style="display:inline;" height="217" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_5D0CD0D8.png" width="511" /&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 title="image" style="display:inline;margin:0px 20px 0px 0px;" height="240" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_094957BD.png" width="130" align="left" /&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%20" 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;p&gt;&amp;#160;&lt;/p&gt;  &lt;blockquote&gt;&lt;/blockquote&gt;  &lt;p&gt;&amp;#160;&lt;/p&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;#160; column name&amp;#160; would consist of type name and “ID” suffix&amp;#160; (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;#160;&amp;#160; (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;&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;&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;#160; 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;#160; 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;&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;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CustomerConfiguration.ReferencePerson.xml&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&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;&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 title="image" style="display:inline;" height="75" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/image_thumb_6638E64C.png" width="640" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;p&gt;&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 class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:47cff7c6-7bc1-4aa6-adb5-3e18f27576a7" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&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><item><title>Dependency injection in real world</title><link>http://feedproxy.google.com/~r/vuscode/~3/q91DrLNVpVk/dependency-injection-in-real-world.aspx</link><pubDate>Tue, 23 Dec 2008 10:45:13 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:557</guid><dc:creator>malovicn</dc:creator><slash:comments>7</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=557</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/12/23/dependency-injection-in-real-world.aspx#comments</comments><description>&lt;p&gt;Patrick left a comment on &lt;a target="_blank" href="http://blog.vuscode.com/malovicn/archive/2008/06/07/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx"&gt;one of my previous blog posts&lt;/a&gt; asking a couple of very interesting questions that I’ve been asking myself too:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Is service locator legitimate way of doing IoC?&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;(I’ll use example code from that blog post as a base for my today blog post so in case you are idle enough you can go and check it out)&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Dependency injection primer&lt;/h1&gt;  &lt;p&gt;Let me start with an example how “real” dependency injection implementation code from my blog post could look like:&lt;/p&gt;  &lt;pre class="c-sharp"&gt;using System;
using System.Collections.Generic;

namespace Example.UserManager
{
    public class UserManagerIoC
    {
        private readonly IUserProvider userProvider;

        public UserManagerIoC(IUserProvider userProvider)
        {
            this.userProvider = userProvider;
        }

        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            var userCollection = this.userProvider.GetUserCollection();
            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.Name.StartsWith(userName) &amp;amp;&amp;amp; user.LastActivity &amp;gt; DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
    }
}&lt;/pre&gt;

&lt;p&gt;As we can see from the simple code above, code has one constructor which accepts the IUserProvider parameter and then stores its pointer to a field&amp;#160; so it can be used&amp;#160; later in a method which performs some kind of business logic.&lt;/p&gt;

&lt;p&gt;Key concept here to be noticed is that class have literally no clue where from and how userProvider would get injected.&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;How DI based unit test looks like?&lt;/h2&gt;

&lt;p&gt;I’ll use &lt;a target="_blank" href="http://blog.vuscode.com/malovicn/archive/2008/05/18/design-for-testability-microsoft-unity-part-7.aspx"&gt;Microsoft Unity&lt;/a&gt; and &lt;a target="_blank" href="http://blog.vuscode.com/malovicn/archive/2007/02/05/tdd-rhino-mocks-part-1-introduction.aspx"&gt;Rhino mocks&lt;/a&gt; to write a test for the dependency injection primer. &lt;/p&gt;

&lt;p&gt;Here it is:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System.Collections.Generic;
using Example.UserManager;
using Microsoft.Practices.Unity;
using NUnit.Framework;
using Rhino.Mocks;

namespace UserManager.Test.IoC
{
    [TestFixture]
    public class UserManagerTestIoC
    {
        private MockRepository mockRepository;
        private IUnityContainer unityContainer;

        [SetUp]
        public void Test_Init()        
        {
            this.mockRepository = new MockRepository();
            this.unityContainer = new UnityContainer();
        }

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            var userProvider = this.mockRepository.DynamicMock&amp;lt;IUserProvider&amp;gt;();
            // injecting to unity container mocked instance of user provider
            this.unityContainer.RegisterInstance(userProvider);
            
            using (this.mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List&amp;lt;User&amp;gt;());
            }
            using (this.mockRepository.Playback())
            {
                // using IoC container for UserManager construction 
                var userManager = this.unityContainer.Resolve&amp;lt;UserManagerIoC&amp;gt;();
                
                // and then performing tested code 
                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(&amp;quot;X&amp;quot;);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  
    }
}&lt;/pre&gt;

&lt;p&gt;What I did in that test:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I am instantiating UnityContainer in test set up to be used as IoC container. &lt;/li&gt;

  &lt;li&gt;In first line of test&amp;#160; method I am using Rhino mocks to create mock of IUserProvider and then I inject that mock to Unity IoC container &lt;/li&gt;

  &lt;li&gt;In a first line of recording block, I set expectation that empty user collection would be returned &lt;/li&gt;

  &lt;li&gt;In playback block, I get an instance of UserManagerIoC class by using IoC container Resolve factory method. &lt;strong&gt;(KEY POINT)&lt;/strong&gt; &lt;/li&gt;

  &lt;li&gt;IoC container would then: 
    &lt;ul&gt;
      &lt;li&gt;examine the constructor of UserManagerIoC class, &lt;/li&gt;

      &lt;li&gt;see that IUserProvider parameter is requested &lt;/li&gt;

      &lt;li&gt;try to find in IoC container registered service implementing IUserProvider interface &lt;/li&gt;

      &lt;li&gt;mocked instance we injected at the beginning of the test would be found &lt;/li&gt;

      &lt;li&gt;mocked instance would be injected to UserManagerIoC &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Method would be executed and the expected number of users checked &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;NOTE #1: You could get away from explicit dependency mocking by using &lt;a target="_blank" href="http://blog.vuscode.com/malovicn/archive/2008/06/08/design-for-testability-auto-mocking-container-amc-part-9.aspx"&gt;AutoMockingContainer&lt;/a&gt; but I decide to do it anyhow in this post in order to increase example readability. &lt;/p&gt;

&lt;p&gt;NOTE #2: You could also opt to use var userManager = new UserManager(userProvider) but this is not something typically you would do because userProvider can have it’s own dependencies and so on… Not using IoC container in the test would mean not using one of its most important features: auto dependency resolution. &lt;/p&gt;

&lt;h2&gt;Dependency injection upsides and downsides&lt;/h2&gt;

&lt;p&gt;As we can see, we were able to keep UserManager light and ignorant about IoC infrastructure, while utilizing the benefits dependency injection provides us (increased testability in this example)&lt;/p&gt;

&lt;p&gt;Still there are couple of problems (not sure if I can call them like this) related to this implementation which I’ve witnessed in last couple of months and which can be summarized as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Brownfield scenarios&lt;/strong&gt; 

    &lt;br /&gt;UserManager is already existing class built without having dependency injection on mind (no constructor exposing abstracted dependencies). While it is hard to sell the business value of refactoring UserManager internals to expose dependencies through constructor (sell tagline: to test it) it is mission impossible getting approval for updating all of the million places&amp;#160; currently doing the UserManager um = new UserManager() to become unityContainer.Resolve&amp;lt;UserManager&amp;gt;() (Sith language : “What’s the business value?”) and without that change no DI going to happen. &lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;Code monkey scenarios 
      &lt;br /&gt;&lt;/strong&gt;Vast majority of developers I know don’t get the IoC, TDD etc, which means that one would spend ton of time answering the 

    &lt;br /&gt;“Why I can not just new the instance?”, “This is clearly an overkill…”, “Here it is him with his damn patterns making my life miserable”, “Why I need to decouple DB from my&amp;#160; unit tests at all?”.. 

    &lt;br /&gt;Although this reason might look “not-so-important”, if you are not lucky to work in TDD friendly environment, if you are working in company which DEV teams span across the globe this could be real show stopper. &lt;/li&gt;

  &lt;li&gt;&lt;strong&gt;“TDD == unit test” 
      &lt;br /&gt;&lt;/strong&gt;If you are doing unit tests AFTER the code is been done then it is very hard to sell to PMs the need for “all that complexity”. 

    &lt;br /&gt;In other words, if they don’t get that in TDD the most important thing is not the “T” (test) but the “DD” (driven design) whole DI thing start to get harder to be sold &lt;/li&gt;

  &lt;li&gt;“Why IoC framework X?” 
    &lt;br /&gt;”Why UnityContainer?” “Why not Castle?” “Why not Spring?” “Why not StructureMap?” “On my previous job I worked with XYZ and it is the best…” &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h1&gt;ServiceLocator based dependency injection&lt;/h1&gt;

&lt;p&gt;Luckily, I think I found a way how to go around the restrictions mentioned above with keeping the dependency injection in place and high testability. I’ve wrote in more details in my DFT blog post series so here I’ll just summarize it…&lt;/p&gt;

&lt;p&gt;The key points that solution has to achieve are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Core code implementation has to utilize dependency injection &lt;/li&gt;

  &lt;li&gt;Code has to be “open for testing” but “close for development”&amp;#160; (yes, I am aware how stupid this might sound and it it stupid thing – details bellow ) &lt;/li&gt;

  &lt;li&gt;DI enabling existing code is not allow to cause any breaking compatibility issues (KIC - “keep it cheap” design principle) &lt;/li&gt;

  &lt;li&gt;No dependency on any particular IoC framework 
    &lt;br /&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lets take a look at the same primer I’ve done with DI this time implemented using service locator &lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System;
using Facade;

namespace Example.UserManager
{
    public class UserManagerSL
    {
        private readonly IUserProvider userProvider;

        public UserManagerSL(): this (ServiceLocator.Retrieve&amp;lt;IUserProvider&amp;gt;())
        {
        }

        internal UserManagerSL(IUserProvider userProvider)
        {
            this.userProvider = userProvider;
        }

        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            var userCollection = this.userProvider.GetUserCollection();
            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.Name.StartsWith(userName) &amp;amp;&amp;amp; user.LastActivity &amp;gt; DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Main differences (compared to dependency injection primer) are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We still have public parameter less constructor 
    &lt;br /&gt;That parameter less&amp;#160; constructor uses ServiceLocator to retreive instace of IUserProvider on a same way UnityContainer retrieved it in previous test. 

    &lt;br /&gt;ServiceLocator is just a Facade wrapper around IoC container encapsulating the type of container and hiding not used features. 

    &lt;br /&gt;&lt;strong&gt;Achieved design goal: “Keep it cheap” 
      &lt;br /&gt;&lt;strong&gt;Achieved design goal: “No dependency on particular IoC framework”&lt;/strong&gt;&lt;/strong&gt; 

    &lt;br /&gt;&lt;/li&gt;

  &lt;li&gt;In some bootstrapper class tied to app start event I will have to define ServiceLocator mapping for service implementing the IUserProvider so the code would work normally like it was working before the dependency injection &lt;strong&gt;&lt;strong&gt;
        &lt;br /&gt;&lt;/strong&gt;&lt;/strong&gt;&lt;/li&gt;

  &lt;li&gt;Constructor taking IUserProvider parameter is now internal. 
    &lt;br /&gt;The assembly containing UserManagerSL class would contain next attribute 

    &lt;pre class="c-sharp"&gt;[assembly: InternalsVisibleTo(&amp;quot;UserManager.Test.SL&amp;quot;)]&lt;/pre&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  &lt;p&gt;Result of this attribute would be that this constructor would be:&lt;/p&gt;

  &lt;p&gt;- visible to test assembly containing test methods using UserManagerSL 
    &lt;br /&gt;- not visible to any code outside of that test assembly (none of the “core DEV” would be aware of it)&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Achieved design goal: “Open for test, close for development” 
      &lt;br /&gt;&lt;/strong&gt;&lt;strong&gt;Achieved design goal: “Dependency injection used in code”&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;How ServiceLocator based test looks like?&lt;/h2&gt;

&lt;p&gt;Here are two examples how the service locator code can be tested..&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h3&gt;“White box” service locator test style &lt;/h3&gt;

&lt;pre class="c-sharp"&gt;using System.Collections.Generic;
using Example.UserManager;
using Facade;
using NUnit.Framework;
using Rhino.Mocks;

namespace UserManager.Test.SL
{
    [TestFixture]
    public class UserManagerTestSL
    {
        private MockRepository mockRepository;
        private IUserProvider userProvider;

        [SetUp]
        public void Test_Init()        
        {
            this.mockRepository=new MockRepository();

            // registering mock of IUserProvider with ServiceLocator
            this.userProvider = this.mockRepository.DynamicMock&amp;lt;IUserProvider&amp;gt;();
            ServiceLocator.InjectStub(this.userProvider);
        }

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection_WithSL()
        {
            using (this.mockRepository.Record())
            {
                Expect.Call(this.userProvider.GetUserCollection())
                    .Return(new List&amp;lt;User&amp;gt;());
            }
            using (this.mockRepository.Playback())
            {
                // using internal constructor
                var userManager = new UserManagerSL();
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days(&amp;quot;X&amp;quot;);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;In this testing style we feed the service locator with the list of internal dependencies we know it is been used by the tested code and then in our test method we totally don’t care about dependency injection (constructors used are empty, no service locator usage anywhere outside of SetUp method)&lt;/p&gt;

&lt;p&gt;I personally don’t like this style of testing (based on intimate knowledge of tested code) but I’ve seeing it working in the past.&lt;/p&gt;

&lt;h3&gt;Using internal constructor&lt;/h3&gt;

&lt;p&gt;Second approach is based on the fact that internal constructor is accessible to test assembly which makes test built on this way very simple&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System.Collections.Generic;
using Example.UserManager;
using NUnit.Framework;
using Rhino.Mocks;

namespace UserManager.Test.SL
{
    [TestFixture]
    public class UserManagerTestSL
    {
        private MockRepository mockRepository;

        [SetUp]
        public void Test_Init()        
        {
            this.mockRepository=new MockRepository();
        }

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            IUserProvider userProvider = mockRepository.DynamicMock&amp;lt;IUserProvider&amp;gt;();

            using (mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List&amp;lt;User&amp;gt;());
            }
            using (mockRepository.Playback())
            {
                // using internal constructor
                var userManager = new UserManagerSL(userProvider);
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days(&amp;quot;X&amp;quot;);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }
    }
}&lt;/pre&gt;

&lt;p&gt;In this example we don’t use at all service locator. Instead we simply inject mocked instance of user provider to internal constructor. All of the downsides of this approach (mentioned in dependency injection note #2) are applicable here to.&lt;/p&gt;

&lt;h2&gt;Using dependency injection &lt;/h2&gt;

&lt;p&gt;The best thing with my service locator based design approach is that while some of the “not so TDD skilled” developers can do testing on the first two ways, “TDD skilled” developer can still write exactly the same test as the one given in the dependency injection section of this blog post.&lt;/p&gt;

&lt;p&gt;Check it for yourself:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollectio_IoC()
        {
            var userProvider = this.mockRepository.DynamicMock&amp;lt;IUserProvider&amp;gt;();
            // injecting to unity container mocked instance of user provider
            ServiceLocator.InjectStub(userProvider);

            using (this.mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List&amp;lt;User&amp;gt;());
            }
            using (this.mockRepository.Playback())
            {
                // using IoC container for UserManager construction 
                var userManager = ServiceLocator.Retrieve&amp;lt;UserManagerSL&amp;gt;();

                // and then performing tested code 
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days(&amp;quot;X&amp;quot;);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  &lt;/pre&gt;

&lt;h1&gt;Summary&lt;/h1&gt;

&lt;p&gt;Most of the blog posts I’ve seen present an ideal “perfect day” situation setup&amp;#160; for writing the test which is not always the case in real world. &lt;/p&gt;

&lt;p&gt;In this kind of “not-so-perfect” situations, service locator based solution I’ve presented in that blog post allowed me to increase testability and introduce TDD into existing code bases and environments not so much interested in the TDD.&lt;/p&gt;

&lt;p&gt;Source code for this blog post can be found &lt;a target="_blank" href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/SLvsIoC.zip"&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:7d364741-7d40-4edb-9c7b-32515625ff8a" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/TDD" rel="tag"&gt;TDD&lt;/a&gt;,&lt;a href="http://technorati.com/tags/DFT" rel="tag"&gt;DFT&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Service+Locator" rel="tag"&gt;Service Locator&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Dependency+Injection" rel="tag"&gt;Dependency Injection&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Unit+testing" rel="tag"&gt;Unit testing&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rhino+mocks" rel="tag"&gt;Rhino mocks&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=557" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=ybTvOV8p"&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=uloBGTUE"&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=S42uhuXu"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=S42uhuXu" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/q91DrLNVpVk" 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/2008/12/23/dependency-injection-in-real-world.aspx</feedburner:origLink></item><item><title>Fluent NHibernate – NHibernate without configuration files</title><link>http://feedproxy.google.com/~r/vuscode/~3/F1gPRT8vJA0/fluent-nhibernate-nhibernate-without-configuration-files.aspx</link><pubDate>Sun, 31 Aug 2008 10:39:28 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:488</guid><dc:creator>malovicn</dc:creator><slash:comments>11</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=488</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx#comments</comments><description>&lt;p&gt;&lt;img style="margin:0px 20px 20px;" src="http://fluent-nhibernate.googlecode.com/svn/trunk/docs/logo.png" align="right" alt="" /&gt;NHibernate is great, (no doubt about it) but every time I was supposed to work with it, the fact that I had to manually type in all those xml configuration entries was something I &lt;strong&gt;really &lt;/strong&gt;didn’t like at all. &lt;/p&gt;  &lt;p&gt;The most important complains I personally have on NHibernate configuration files are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It is error prone &lt;/li&gt;    &lt;li&gt;Errors in configuration file can be hard to trace &lt;/li&gt;    &lt;li&gt;It is not refactoring friendly &lt;/li&gt;    &lt;li&gt;It is not C#, it is XML :-) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I believe that the most important reason why NHibernate is not more widely adopted by general DEV population is exactly the “Java XML configuration” PIA feeling you have while working with it. &lt;/p&gt;  &lt;p&gt;Great news for all of us from that group: NHibernate is possible to be used WITHOUT configuration files! &lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Who, what and where?&lt;/h1&gt; &lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/08/08/introducing-fluent-nhibernate.aspx"&gt;&lt;/a&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_2.png"&gt;&lt;img title="image" style="border-top-width:0px;border-left-width:0px;border-bottom-width:0px;margin:0px 20px 20px 0px;border-right-width:0px;" height="244" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb.png" width="180" align="left" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Jeremy Miller&lt;/a&gt; coded initial bits of the Fluent NHibernate project and then &lt;a title="http://blog.jagregory.com/2008/08/08/introducing-fluent-nhibernate/" href="http://blog.jagregory.com/2008/08/08/introducing-fluent-nhibernate/"&gt;James Gregory&lt;/a&gt; with couple of guys more bring the project to Google code and they started finalizing it. OSS rules!&lt;/p&gt;  &lt;p&gt;So, if you go to &lt;a title="http://code.google.com/p/fluent-nhibernate/" href="http://code.google.com/p/fluent-nhibernate/"&gt;http://code.google.com/p/fluent-nhibernate/&lt;/a&gt; you would see names of other project members together with the simple code illustrating the goal fluent nhibernate project tries to achieve.&lt;/p&gt;  &lt;p&gt;As with the most OSS projects, to get the source code of FNH, download it from Subversion trunk located at &lt;strong&gt;&lt;em&gt;http&lt;/em&gt;&lt;/strong&gt;://fluent-nhibernate.googlecode.com/svn/trunk/&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;p&gt;Solution file consist of couple of projects: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;LIb solution folder contains DLL you would be using in your application. &lt;/li&gt;    &lt;li&gt;Test project containing a bunch of unit tests which you can use as starting point to get detail understanding on how the things works. &lt;/li&gt;    &lt;li&gt;Quick start project which highlights most important concepts you need to start using NHibernate &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Note: Project is initially built with NHibernate 2.0 which collides with &lt;a href="http://sourceforge.net/projects/nhcontrib/" target="_blank"&gt;Linq For NHibernate&lt;/a&gt; (using NHibernate 2.1) so I updated FNH project references to use 2.1 too&amp;#160; &lt;/p&gt;  &lt;h1&gt;Fluent NHibernate in action&lt;/h1&gt;  &lt;h2&gt;Solution project structure&lt;/h2&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_14.png"&gt;&lt;img title="image" style="margin:0px 20px 20px 0px;" height="240" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb_6.png" width="146" align="left" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;In this blog post, I will use the same example &lt;a href="http://jimmynilsson.com/blog/" target="_blank"&gt;Jimmy Nilsson&lt;/a&gt; used in his &lt;a href="http://www.amazon.com/dp/0321268202" target="_blank"&gt;Applying Domain-Driven Design and Patterns: With Examples in C# and .NET&lt;/a&gt; NHibernate chapter so you can compare outcome of my blog post sample it with how it looked in his book (with the configuration files in place).&lt;/p&gt;  &lt;p&gt;Solution file of today’s example contains 3 projects:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;BusinessLayer (“Domain”)      &lt;br /&gt;Contains definitions of entities which we use in modeling business use cases.       &lt;br /&gt;Important to be mentioned here is that BusinessLayer&amp;#160; project doesn’t have any reference to neither other projects of this solution nor the “3pty dlls” such is NHibernate.dll &lt;/li&gt;    &lt;li&gt;NHConfigMappings (“Mapping project”)      &lt;br /&gt;Contains ORM mapping definitions which enables nhibernate to persist to relational DB domain entities &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;NHCongigMappings.Test&lt;/strong&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Contains test fixture illustrating how mappings should be consumed and how nhibernate engine could be initialized without any xml configuration files &lt;/p&gt;  &lt;p&gt;&lt;em&gt;&lt;strong&gt;&lt;font color="#ff0000"&gt;(Source code used in today blog post can be download from &lt;/font&gt;&lt;/strong&gt;&lt;/em&gt;&lt;a href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/NHibernate.zip" target="_blank"&gt;&lt;em&gt;&lt;strong&gt;&lt;font color="#ff0000"&gt;here&lt;/font&gt;&lt;/strong&gt;&lt;/em&gt;&lt;/a&gt;&lt;strong&gt;&lt;font color="#ff0000"&gt;&lt;em&gt;)&lt;/em&gt;&amp;#160;&lt;/font&gt;&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Domain project &lt;/h2&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_4.png"&gt;&lt;img title="image" style="margin:0px 20px 20px 0px;" height="322" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb_1.png" width="640" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;As you can see, it is very simple sample where we have entity customer class containing “embedded” Address value object and referencing the list of reference persons customer contacted.&lt;/p&gt;  &lt;p&gt;Same diagram given in code would look like this&lt;/p&gt;  &lt;pre class="c-sharp"&gt;using System;
using System.Collections.Generic;

namespace CustomerConfiguration
{
    public class Customer
    {
        public virtual Guid Id { get; set; }

        public virtual string CustomerNumber { get; set; }

        public virtual string Name { get; set; }

        public virtual Address CustomerAddress { get; set; }

        public virtual IList ReferencePersons { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;Address type will look like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;namespace CustomerConfiguration
{
    public class Address
    {
        public virtual string Street { get; set; }
        public virtual string PostalCode { get; set; }
        public virtual string Town { get; set; }
        public virtual string Country { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;And ReferencePerson type would look like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System;

namespace CustomerConfiguration
{
    public class ReferencePerson
    {
        public virtual Guid Id { get; set; }

        public virtual string FirstName { get; set; }

        public virtual string SurName { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;As you can see from the code above, NHibernate allows us fully &lt;a href="http://www.jnsk.se/weblog/posts/pocoorpi.htm" target="_blank"&gt;persistent ignorant \POCO&lt;/a&gt; software development: no special attributes, no special base class or interface…&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;Mapping project&lt;/h1&gt;

&lt;p&gt;Once we have domain logic defined, we need to provide information on how NHibernate should map our classes with appropriate DB entities: tables and columns.&lt;/p&gt;

&lt;p&gt;For my example DB would look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_12.png"&gt;&lt;img title="image" style="margin:0px 20px 20px 0px;" height="182" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb_5.png" width="640" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;As you can see, although in my code I have separate Address class I don’t have it in DB. Instead I have it embedded in Customer table as last 4 columns. Also, table names in DB are in plural form while names of classes are in singular form.&lt;/p&gt;

&lt;p&gt;Another small difference here is that in ReferencePerson class has a LastName property while DB has column SurName.&lt;/p&gt;

&lt;h2&gt;Mapping ReferencePerson&lt;/h2&gt;

&lt;p&gt;I won’t throw in here example of how that would look if I would use XML configuration file, because the whole point is to forget that ASAP :) (In case you want to see it, check it out &lt;a href="http://blog.jagregory.com/2008/08/08/introducing-fluent-nhibernate/" target="_blank"&gt;here&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;In order to define NHibernate mapping, in FNH you need to create a mapping class for each one of entities (which is something &lt;a href="http://www.ayende.com/Blog/archive/2008/08/12/On-Fluent-NHibernate.aspx" target="_blank"&gt;Ayende don’t get&lt;/a&gt;). &lt;/p&gt;

&lt;p&gt;That mapping class should inherit from&amp;#160; ClassMap&amp;lt;T&amp;gt; class in order to get access to FHN members providing programmatic access over configuration settings&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using CustomerConfiguration;
using FluentNHibernate.Mapping;

namespace NHConfigMappings
{
    public class ReferencePersonMap : ClassMap&amp;lt;ReferencePerson&amp;gt;
    {
        public ReferencePersonMap()
        {
            TableName = “ReferencePersons”;
            
            Id(x =&amp;gt; x.Id).GeneratedBy.GuidComb()
                .WithUnsavedValue(“00000000-0000-0000-0000-000000000000”);

            Map(x =&amp;gt; x.FirstName).WithLengthOf(50).CanNotBeNull();
            Map(x =&amp;gt; x.LastName,”SurName”).WithLengthOf(50).CanNotBeNull();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Main advantage of &lt;a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank"&gt;fluent interface&lt;/a&gt; is that&amp;#160; it produces code with good readability, which I believe we can see from code snippet above.&lt;/p&gt;

&lt;p&gt;In a class constructor, I am defining:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;What is the name of data table where the class will be persisted. In my example table name and class name differs so I had to define it here, but I think it is good practice to define it always, even they are implicitly the same by the default &lt;/li&gt;

  &lt;li&gt;Which class property should be used as &lt;a href="http://martinfowler.com/eaaCatalog/identityField.html" target="_blank"&gt;Identity Field&lt;/a&gt; populating table PK. In example I took I am using ReferenceMap.Id property where NHibernate generate its value using &lt;a href="http://www.informit.com/articles/article.aspx?p=25862" target="_blank"&gt;GuidComb&lt;/a&gt;&amp;#160; value as performance effective type of GUID values. At the end I defined how unsaved value is looking like so NHibernate would be able to deduct how the class should be persisted (insert or update) &lt;/li&gt;

  &lt;li&gt;That the FirstName property should be mapped to the column with the same name where the column length is 50 characters and null values are not allowed &lt;/li&gt;

  &lt;li&gt;That the LastName property should be mapped to the column named “SurName” with the maximum length of 50 characters without null values being allowed &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In my opinion main advantages here are that the configuration code is human readable and refactoring friendly (if I ever do changes on ReferencePerson class mapping file will be broken so we have “type safe” configuration settings)&lt;/p&gt;

&lt;h2&gt;Mapping Customer&lt;/h2&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Customer class mapping definition is stored in CustomerMap (implementing the ClassMap&amp;lt;Customer&amp;gt; class looking something like this&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using CustomerConfiguration;
using FluentNHibernate.Mapping;

namespace NHConfigMappings
{
    public class CustomerMap : ClassMap&amp;lt;Customer&amp;gt;
    {
        public CustomerMap()
        {
            TableName = “Customers”;
            
            Id(x =&amp;gt; x.Id).GeneratedBy.GuidComb()
                .WithUnsavedValue”00000000-0000-0000-0000-000000000000”);
            
            Map(x =&amp;gt; x.Name).WithLengthOf(50);
            Map(x =&amp;gt; x.CustomerNumber).WithLengthOf(50);
            
	    HasMany&amp;lt;ReferencePerson&amp;gt;(x =&amp;gt; x.ReferencePersons)
                .Access.AsProperty()
                .AsBag().WithKeyColumn(&amp;quot;CustomerId&amp;quot;)
                .Cascade.All();                        
            
            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;/pre&gt;

&lt;p&gt;In a class constructor, I am defining:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The name of table to which this class map &lt;/li&gt;

  &lt;li&gt;Customer.Id as primary key containing guid value &lt;/li&gt;

  &lt;li&gt;Customer.Name is mapped to the Name nvarchar(50) column &lt;/li&gt;

  &lt;li&gt;Customer.CustomerNumber is mapped to the CustomerNumber nvarchar(50) column &lt;/li&gt;

  &lt;li&gt;Customer class contains collection of ReferencePerson instances stored in Customer.ReferencePersons property 
    &lt;br /&gt;which should be mapped in separate table (AsBag())&amp;#160; where role of FK will be performed by ReferencePerson.CustomerId 

    &lt;br /&gt;and with cascading of events (Insert of Customer will result with Insert of ReferencePerson etc) &lt;/li&gt;

  &lt;li&gt;Customer contains property CustomerAddress of type Address as embed value where 
    &lt;ol&gt;
      &lt;li&gt;Address.Street is nvarchar(100) column &lt;/li&gt;

      &lt;li&gt;Address.PostalCode&amp;#160; is nvarchar(6) column &lt;/li&gt;

      &lt;li&gt;Address.Town is nvarchar(30) column &lt;/li&gt;

      &lt;li&gt;Address.Country is nvarchar(50) column &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once again, take a look at the class above. I have just described something which looks like typical use case we face in real world with something which (IMHO) has very high readability and&amp;#160; it is easy to be written&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;Unit testing fluent nhibernate mappings&lt;/h1&gt;

&lt;p&gt;In order to present how those mappings should be used I wrote unit test project which will present: &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;how this mappings are to be used &lt;/li&gt;

  &lt;li&gt;how to configure nhibernate itself without the need for hibernate.cfg.xml file &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For the purpose of this test I choose MS Test just for kicks (although I am mostly using MBUnit )&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;How to initialize nhibernate without hibernate.cfg.xml &lt;/h2&gt;

&lt;p&gt;Due to the fact that initializing nhibernate engine is slow, I am initializing it once per text fixture and in test fixture of this example nhibernate initialization routine in case of fluent nhibernate is a 5 step procedure:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Initialize type implementing IPersistenceConfigurer (MSSqlConfiguration, SQLLiteConfiguration, PostgreSQLConfiguration are currently supported) &lt;/li&gt;

  &lt;li&gt;use instance of that type (in my example instance of MSSqlConfiguration) to preset properties of NHibernate.Configuration instance &lt;/li&gt;

  &lt;li&gt;create instance of FluentHibernate.PersistenceModel type &lt;/li&gt;

  &lt;li&gt;use that instance to load the assembly containing mappings &lt;/li&gt;

  &lt;li&gt;use that instance to inject mappings to nhibernate configuration instance &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;At the end of configuration sequence I have&amp;#160; operational NHibernate configuration instance which I use to create session factory which I then store as a class field. &lt;/p&gt;

&lt;p&gt;Once I have that SessionFactory field in place, each one of the test methods just uses it to create a session needed.&lt;/p&gt;

&lt;p&gt;Let’s take a look at how this initialization routine could look in code&lt;/p&gt;

&lt;pre class="c-sharp"&gt;   
	
	private static ISessionFactory _sessionFactory;

        [ClassInitialize]
        public static void FixtureInit(TestContext testContext)
        {
            // initialize persistance configurer
            IPersistenceConfigurer persistenceConfigurer =
                MsSqlConfiguration
                    .MsSql2005
                    .ConnectionString.Is(
                    “Data Source=.\SQL2008;Initial Catalog=NHibernateBlog;&amp;quot;
		    + &amp;quot;Integrated Security=True”)
                    .ShowSql();

            // initialize nhibernate with persistance configurer properties
            Configuration cfg = persistenceConfigurer
				.ConfigureProperties(new Configuration());

            // add mappings definition to nhibernate configuration
            var persistenceModel = new PersistenceModel();
            persistenceModel.addMappingsFromAssembly
			(Assembly.Load(“NHConfigMappings”));
            persistenceModel.Configure(cfg);

            // set session factory field which is to be used in tests
            _sessionFactory = cfg.BuildSessionFactory();
        } &lt;/pre&gt;

&lt;p&gt;I think code above is simple enough (thanks to FNH) that it doesn’t need any extra explanations about its&amp;#160; concrete implementation.&lt;/p&gt;

&lt;h2&gt;Nhibernate unit test method&lt;/h2&gt;

&lt;p&gt;Now when we have that session factory up and going, we would make only a simple test where we will create a new customer and try to store it in DB.&lt;/p&gt;

&lt;p&gt;That test code could look like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;        [TestMethod]
        public void ReferencePerson_Create_ShouldCreateRowInDb()
        {
            var customer = new Customer
               {
                   Name = “John Doe”,
                   CustomerNumber = “12345”,
                   CustomerAddress = new Address
                                         {
                                             Street = “1st Mayson Street”,
                                             PostalCode = “01754”,
                                             Town = “Maynard”,
                                             Country = “USA”
                                         },
                   ReferencePersons = new List&amp;lt;ReferencePerson&amp;gt;
                                          {
                                              new ReferencePerson
                                                  {
                                                      FirstName = “Nikola”,
                                                      LastName = “Malovic”
                                                  }
                                          }
               };

            ISession session = _sessionFactory.OpenSession();
            Guid id=(Guid)session.Save(customer);
            session.Flush();

            session.Evict(customer);
            
            var customerDB= session.Get&amp;lt;Customer&amp;gt;(id);
            Assert.IsTrue(  customerDB.Id == customer.Id &amp;amp;&amp;amp; customerDB.Name == customer.Name 
                            &amp;amp;&amp;amp; customerDB.CustomerAddress.Street == “1st Mayson Street”
                            &amp;amp;&amp;amp; customerDB.ReferencePersons[0].FirstName == “Nikola”);

        }&lt;/pre&gt;

&lt;p&gt;At the beginning of the test method I create a new customer instance with CustomerAddress data and single ReferencePerson instance in ReferencePersons. &lt;/p&gt;

&lt;p&gt;Then I use the sessionFactory created in test fixture set up, and create a session which then I use to persist customer instance. As a result of that persistence method call I am getting customer identity value used as PK value in DB.At the end of that persistence code I just flush the session in order to commit the changes.&lt;/p&gt;

&lt;p&gt;Now when (hopefully) our customer is saved I need to test that and the usual way of testing save is to try to load the data from DB. That’s why I remove the customer instance from NHibernate Identity Map “cache” so I won’t get results from memory and then I am trying to retrieve data using the identity value I retrieved during persistence.&lt;/p&gt;

&lt;p&gt;With the retrieved customer data I do just quick value check (in real world test this check would look different). &lt;/p&gt;

&lt;p&gt;Test will pass therefore if retrieved data will match the data of customer instance created in this test.&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;Running the test&lt;/h2&gt;

&lt;p&gt;Once I run the test, I got successful test&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_16.png"&gt;&lt;img title="image" style="margin:0px 20px 20px 0px;" height="79" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb_7.png" width="640" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;And fast look at the DB shows that data are persisted&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_18.png"&gt;&lt;img title="image" style="margin:0px 20px 20px 0px;" height="186" alt="image" src="http://blog.vuscode.com/blogs/blogs/malovicn/WindowsLiveWriter/FluentNHibernateNHibernatewithoutconfigu_7C63/image_thumb_8.png" width="640" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Test passed!&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;h1&gt;Conclusion &lt;/h1&gt;

&lt;p&gt;Purpose of this blog post was to present a way of using NHibernate different then the standard xml configuration approach most of people use right now working with NHibernate. &lt;/p&gt;

&lt;p&gt;I hope you can see for yourself that it is VERY possible to use NHibernate without a single configuration file on very DEV friendly and intuitive way.&lt;/p&gt;

&lt;p&gt;The example I presented here is just tip of the iceberg so I strongly encourage you to sync Fluent NHibernate source code and play with quick start and test projects.&lt;/p&gt;

&lt;p&gt;Here are also some links you can check out too:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/06/18/working-faster-and-fewer-mapping-errors-with-nhibernate.aspx" target="_blank"&gt;Working faster and fewer mapping errors with NHibernate&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;&lt;a href="http://www.IAmNotMyself.com/2008/08/07/SkinningTheCatWithFluentNHibernate.aspx"&gt;Skinning the Cat with Fluent NHibernate&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;

  &lt;li&gt;
    &lt;p&gt;&lt;a href="http://www.lostechies.com/blogs/chad_myers/archive/2008/08/18/fluent-nhibernate-configuration.aspx" target="_blank"&gt;Fluent Nhibernate configuration&lt;/a&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Happy Hibernating!&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:01afaf9f-cceb-4d88-9a9e-92679c61f56f" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/fluent+nhibernate" rel="tag"&gt;fluent nhibernate&lt;/a&gt;,&lt;a href="http://technorati.com/tags/nhibernate+2" rel="tag"&gt;nhibernate 2&lt;/a&gt;,&lt;a href="http://technorati.com/tags/PI" rel="tag"&gt;PI&lt;/a&gt;,&lt;a href="http://technorati.com/tags/POCO" rel="tag"&gt;POCO&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=488" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=UGNzJxoO"&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=AJ8tSrFZ"&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=YwAEHnVA"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=YwAEHnVA" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/F1gPRT8vJA0" 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/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2008/08/31/fluent-nhibernate-nhibernate-without-configuration-files.aspx</feedburner:origLink></item><item><title>Model View Presenter (MVP) – Tips from trenches (TFT) – Working with HttpContext (Part 2)</title><link>http://feedproxy.google.com/~r/vuscode/~3/lnwWiandzRM/model-view-presenter-tips-from-trenches-tft-base-types-part-1.aspx</link><pubDate>Wed, 30 Jul 2008 10:49:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:460</guid><dc:creator>malovicn</dc:creator><slash:comments>7</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=460</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/07/30/model-view-presenter-tips-from-trenches-tft-base-types-part-1.aspx#comments</comments><description>Today’s hurdle: Using HttpContext without System.Web

One of the principles I really feel strong about can be formulated like this:”Presenter is not allowed to reference System.Web assembly at all”. 

Main reason why I feel so strong about that, is based on the fact that once referenced System.Web enables developers in your team to use types from that assembly (HttpContext, Session, Query, Cache etc) and we all know what PITA those types can be when testing Presenters.

Here’s very simple example I’ll use in today’s post: 

Imagine you have a presenter which based on value of some query parameter is performing some redirecting or updating UI elements. 

The easiest way (referencing the System.Web into presenter) will enable very easy implementation of required functionality but testing that code will require things like creating fake web context which IMHO is good sign of of important web test smell. 

To check out rest of my MVP (Model View Presenter) blog post please visit my blog page (thanks to feedburner limit of 500K per feed) ...(&lt;a href="http://blog.vuscode.com/malovicn/archive/2008/07/30/model-view-presenter-tips-from-trenches-tft-base-types-part-1.aspx"&gt;read more&lt;/a&gt;)&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=460" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=4cyL82qu"&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=tfVyXmnD"&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=Fvi6hwnD"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=Fvi6hwnD" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/lnwWiandzRM" 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/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2008/07/30/model-view-presenter-tips-from-trenches-tft-base-types-part-1.aspx</feedburner:origLink></item><item><title>Model View Presenter (MVP) – Tips from trenches (TFT) – Base types(Part 1)</title><link>http://feedproxy.google.com/~r/vuscode/~3/mb9SDYqrW7c/model-view-presenter-mvp-tips-from-trenches-tft-base-types-part-1.aspx</link><pubDate>Sun, 27 Jul 2008 20:47:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:461</guid><dc:creator>malovicn</dc:creator><slash:comments>10</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=461</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/07/27/model-view-presenter-mvp-tips-from-trenches-tft-base-types-part-1.aspx#comments</comments><description>RAD tooling style Microsoft is supporting last couple of years usually leads to the code where presentation and bossiness logic are mixed and tightly coupled which makes testability, maintainability and sustainability much more harder then they should be. In case you’ve had to work in the past with web pages containing couple of thousands lines in code behind you will know exactly what problems I am referring to here. In case not, please let me know what is the name of the place where you work :)

One way to tackle that is using the Model View Presenter UI design pattern which provides clean separation between UI and domain logic and as a result of that come testability of the “UI code”, SRP and SOC principles appliance, clean domain model etc… 

To check out rest of my MVP (Model View Presenter) blog post please visit my blog page (thanks to feedburner limit of 500K per feed) ...(&lt;a href="http://blog.vuscode.com/malovicn/archive/2008/07/27/model-view-presenter-mvp-tips-from-trenches-tft-base-types-part-1.aspx"&gt;read more&lt;/a&gt;)&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=461" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=rSzkJvri"&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=6uR5zveJ"&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=xSiYvcQg"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=xSiYvcQg" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/mb9SDYqrW7c" 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/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2008/07/27/model-view-presenter-mvp-tips-from-trenches-tft-base-types-part-1.aspx</feedburner:origLink></item><item><title>Model View Presenter (MVP) – Tips from trenches (TFT) - Announcement</title><link>http://feedproxy.google.com/~r/vuscode/~3/rhboYCsHhy0/model-view-presenter-mvp-tips-from-trenches-tft-announcement.aspx</link><pubDate>Sun, 06 Jul 2008 07:26:04 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:440</guid><dc:creator>malovicn</dc:creator><slash:comments>5</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=440</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/07/06/model-view-presenter-mvp-tips-from-trenches-tft-announcement.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;I have blogged already in the past about &lt;a href="http://blog.vuscode.com/malovicn/archive/2006/10/10/Model-View-Presenter-_2800_MVP_2900_-pattern.aspx"&gt;MVP basics&lt;/a&gt;, &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/12/18/model-view-presenter-mvp-vs-model-view-controller-mvc.aspx"&gt;MVP vs MVC&lt;/a&gt;, &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/11/04/model-view-presenter-mvp-design-pattern-close-look-part-2-passive-view.aspx"&gt;MVP Passive View&lt;/a&gt; and &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/10/25/model-view-presenter-mvp-design-pattern-close-look-part-1-passive-view.aspx"&gt;MVP Supervising Controller&lt;/a&gt; but recently I had some interesting experiences in applying MVP into real world applications and from that endeavor I learned couple of things and get answers on couple of common questions which I would like to share with community.&lt;/p&gt;  &lt;p&gt;To me, the most interesting part of this experience was that some of my MVP based coding was done using &lt;a href="http://www.codeplex.com/websf" target="_blank"&gt;Web Client Software Factory&lt;/a&gt; but part of MVP coding was done without it, so I had to “port” WCSF features to standard asp net application. I would describe pieces of that port which (I guess) would be interesting for the ones not being able to sell WCSF to their managers but still wanting to use MVP in their ASP NET development.&lt;/p&gt;  &lt;p&gt;Another thing I would try to explain is something a lot of people don’t know: Microsoft MVC .NET framework consist of two separate parts: MVC &lt;strong&gt;and &lt;/strong&gt;routing engine. In other words, routing engine is &lt;strong&gt;not&lt;/strong&gt; part of MVC design pattern and it can be used with WebForms too…&lt;/p&gt;  &lt;p&gt;Another very important thing in real world MVP development I would try to demo is how to introduce MVP pattern usage in legacy components where the legacy model is not written in decoupled manner (Separate interface, Adapter and Translator design patterns)&lt;/p&gt;  &lt;p&gt;Last, but not the least, I would show how MVP pattern is looking combined with ServiceLocator I presented in Design For Testability blog post series and show examples on how to test MVP&lt;/p&gt;  &lt;p&gt;Once I finish presenting all this, I would use presented concepts in showing how “&lt;a href="http://www.codeplex.com/mvcsamples" target="_blank"&gt;one interesting &amp;quot;real world&amp;quot; example&lt;/a&gt;” would look like done with MVP pattern and standard WebForms&lt;/p&gt;  &lt;p&gt;So, MVP fans stay tuned for the posts to come very fast. People not interested in MVP, please be patient… I just need to nail down MVP , “once for all” :)&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Disclaimer: &lt;/strong&gt;The purpose of this blog post series will &lt;strong&gt;not &lt;/strong&gt;be showing that MVC based web development is worst then the MVP one. MVC is awesome but unfortunately requires too big investments to be introduced in existing large web forms web applications (most noticeably the need for redesigning all code which relies on page event life cycle). For those brownfield scenarios, I found MVP much easier to be implemented and adopted by webform developers then the MVC. &lt;/p&gt;  &lt;div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:368763a3-dc2a-499d-984a-9110b8cdc221" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/MVP.+ModelViewPresenter" rel="tag"&gt;MVP. ModelViewPresenter&lt;/a&gt;,&lt;a href="http://technorati.com/tags/TFT" rel="tag"&gt;TFT&lt;/a&gt;,&lt;a href="http://technorati.com/tags/malovic" rel="tag"&gt;malovic&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=440" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=5hyvti42"&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=5GC6MdS7"&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=kAPf6FNh"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=kAPf6FNh" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/rhboYCsHhy0" 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/News/default.aspx">News</category><category domain="http://blog.vuscode.com/malovicn/archive/tags/Development/default.aspx">Development</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2008/07/06/model-view-presenter-mvp-tips-from-trenches-tft-announcement.aspx</feedburner:origLink></item><item><title>Adobe Air 2008 Tour – Prague</title><link>http://feedproxy.google.com/~r/vuscode/~3/gBtdcgmmvtk/adobe-air-2008-tour-prague.aspx</link><pubDate>Tue, 10 Jun 2008 09:56:00 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:430</guid><dc:creator>malovicn</dc:creator><slash:comments>5</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=430</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/06/10/adobe-air-2008-tour-prague.aspx#comments</comments><description>For a few of you reading my blog, this blog post would most definitely come as a big surprise knowing how passionate I am about SIlverlight and all related stuff. Well, although I believe that the real thing is Silverlight, I wanted to check out how the...(&lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/10/adobe-air-2008-tour-prague.aspx"&gt;read more&lt;/a&gt;)&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=430" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=tq0hJn0o"&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=oBLdx7FM"&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=OZ1jUFoU"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=OZ1jUFoU" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/gBtdcgmmvtk" height="1" width="1"/&gt;</description><category domain="http://blog.vuscode.com/malovicn/archive/tags/Tools/default.aspx">Tools</category><category domain="http://blog.vuscode.com/malovicn/archive/tags/News/default.aspx">News</category><feedburner:origLink>http://blog.vuscode.com/malovicn/archive/2008/06/10/adobe-air-2008-tour-prague.aspx</feedburner:origLink></item><item><title>Design for testability – Auto Mocking Container (AMC) – Part 9</title><link>http://feedproxy.google.com/~r/vuscode/~3/dO9DGlG1-Bk/design-for-testability-auto-mocking-container-amc-part-9.aspx</link><pubDate>Sun, 08 Jun 2008 22:49:47 GMT</pubDate><guid isPermaLink="false">4fad33ed-6fa7-4667-b447-1fa3be86b49e:425</guid><dc:creator>malovicn</dc:creator><slash:comments>5</slash:comments><wfw:commentRss>http://blog.vuscode.com/malovicn/rsscomments.aspx?PostID=425</wfw:commentRss><comments>http://blog.vuscode.com/malovicn/archive/2008/06/08/design-for-testability-auto-mocking-container-amc-part-9.aspx#comments</comments><description>&lt;p&gt;&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;On my quest to design for testability, I&amp;#39;ve already covered: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Part 1 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/12/01/designing-for-testability-an-valid-architecture-choice.aspx"&gt;Separation of concerns (SOC) by encapsulating DAL code in internal provider class&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 2 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/12/02/designing-for-testability-an-valid-architecture-choice-part-2.aspx"&gt;Decoupling manager and provider class (introducing the IProvider)&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 3 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2007/12/02/designing-for-testability-an-valid-architecture-choice-part-3.aspx"&gt;Decoupling manager from it consumers (introducing the IManager)&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 4 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/02/13/design-for-testability-dependency-injection-frameworks-part-4.aspx"&gt;Design for testability - Dependency Injection Frameworks&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 5 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/02/20/design-for-testability-castle-windsor-part-5.aspx"&gt;Design for testability - Castle Windsor&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 6 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/02/25/design-for-testability-structure-map.aspx"&gt;Design for testability - Structure map&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 7 - &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/05/18/design-for-testability-microsoft-unity-part-7.aspx"&gt;Design for testability - Microsoft Unity&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;Part 8 – &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/07/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx"&gt;Design for testability - Transparent and opaque dependencies&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;My today’s post would be covering AutoMockingContainer (AMC) in both “standard” and “service locator based” versions&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;What is auto mocking container (AMC)?&lt;/h1&gt;  &lt;p&gt;I’ll use the example from &lt;a href="http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx" target="_blank"&gt;original Elutian blog post&lt;/a&gt; (where the concept of AMC is first mentioned) where the test setup code looks like this:&lt;/p&gt;  &lt;pre class="c-sharp"&gt;[SetUp]
public void Setup()
{
  _service1 = _mocks.CreateMock&amp;lt;IService1&amp;gt;();
  _service2 = _mocks.CreateMock&amp;lt;IService2&amp;gt;();
  _service3 = _mocks.CreateMock&amp;lt;IService3&amp;gt;();
  _serviceWeAreTesting = 
       new DefaultServiceWeAreTesting
            (_service1, _service2, _service3);
}&lt;/pre&gt;

&lt;p&gt;This example applies transparent dependency injection style described in previous post with a class expose a constructor accepting many interface parameters &amp;quot;(“services”) to which class functionality is dependable on.&amp;#160; On first look, there is nothing wrong with the example above but once you would be doing serious testing you would probably find out two things:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;(PIA) during test creation you would probably feel that it is too much “plumbing” code to be done to support testing &lt;/li&gt;

  &lt;li&gt;(REAL PIA) long after once the tests would be done someone would add to that class constructor another parameter (“service4”) and each one of the tests you created would start crashing although probably the functionality you were testing is not relying on _service4 at all. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To tackle those two issues, smart people at Elutian combined Rhino mocks and Windsor container to tackle those problems. &lt;/p&gt;

&lt;p&gt;Using AMC the same test setup code would look like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;[SetUp] 
public void Setup() 
{ 
  _mocks = new MockRepository(); 
  _container = new AutoMockingContainer(_mocks); 
  _service = _container.Create&amp;amp;lt;DefaultServiceWeAreTesting&amp;amp;gt;(); 
} &lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;As you can see, in case of AMC we construct AutoMockingContainer with MockRepository instance thrown as parameter. &lt;/p&gt;

&lt;p&gt;That allow’s us to replace explicit mock creation and concrete constructor invocation with AMC container Create method which accept as generic type parameter the type we plan to test. &lt;/p&gt;

&lt;p&gt;Windsor would then find out the constructor which needs to be used and for each one of the service interfaces (if they are not in container) would create a dynamic mock class implementing given interface (thanks to Rhino mocks). &lt;/p&gt;

&lt;p&gt;so now when we have this initialized writing the test is much simpler and looks like this (taken from the same Elutian blog post)&lt;/p&gt;

&lt;pre class="c-sharp"&gt;[Test]
public void DoWork_Always_AsksOtherServices()
{
  using (_mocks.Unordered())
  {
    _container.Get&amp;amp;lt;Service1&amp;amp;gt;().DoWork();
    _container.Get&amp;amp;lt;Service2&amp;amp;gt;().DoWork();
    _container.Get&amp;amp;lt;Service3&amp;amp;gt;().DoWork();
  }
  _mocks.ReplayAll();
  _service.DoWork();
  _mocks.VerifyAll();
}&lt;/pre&gt;

&lt;p&gt;As you can see, we are not explicitly constructing service class and registering services to container. AMC container already created instance and add components to container in setup method so all we need to do in test is to use them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Obviously:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is much shorter to be written –&amp;gt; issue #1 is solved. &lt;/p&gt;

&lt;p&gt;Even if we would add additional&amp;#160; constructor parameter the AMC would recognize that IService4 was added and it would add its mock to container effectively preserving the test not depending on IService4 runable&amp;#160; –&amp;gt; issue # 2 resolved&lt;/p&gt;

&lt;p&gt;(To get AMC source code which you can compile on your box and use, click &lt;a href="http://blog.eleutian.com/ct.ashx?id=762249da-e25a-4503-8f20-c6d59b1a69bc&amp;amp;url=http%3a%2f%2fblog.eleutian.com%2fdownload%2fAutoMockingContainer.zip" target="_blank"&gt;here&lt;/a&gt;) &lt;/p&gt;

&lt;h1&gt;Auto mocking container and Unity&lt;/h1&gt;

&lt;p&gt;As I mentioned above, the AMC solution given above is for Castle Windsor IoC framework and my IoC framework lately become Microsoft Unity (due to the reasons stated in &lt;a title="http://blog.vuscode.com/malovicn/archive/2008/05/18/design-for-testability-microsoft-unity-part-7.aspx" href="http://blog.vuscode.com/malovicn/archive/2008/05/18/design-for-testability-microsoft-unity-part-7.aspx" target="_blank"&gt;DFT Unity post&lt;/a&gt;), so I did little search for Unity AMC and found out that &lt;a 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 implemented it already&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Roy provided in that blog post example how test looks:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;[Test]
public void MockTwoDependenciesForAConstructor()
{
	MockRepository mocks = new MockRepository();
	AutoMockingUnityContainer container =
        	new AutoMockingUnityContainer(mocks);

	container.WillReturnAStubFor&amp;lt;ILogger&amp;gt;();
        container.WillReturnAStubFor&amp;lt;IEmailer&amp;gt;();

	using (mocks.Record())
	{   
		//Tell our mock to return true when this method is called
        	container.Resolve&amp;lt;ILogger&amp;gt;().IsLogFileFull();
                LastCall.Return(true);	
	}

	//runner class takes both of these mocks in its constructor
        Runner runner = container.Resolve&amp;lt;Runner&amp;gt;();
        Assert.IsNotNull(runner);
}&lt;/pre&gt;

&lt;p&gt;Well, although his implementation is VERY cool way of “create mock and inject it to container”&amp;#160; it is not (at least how I get it) the AMC like the one Elutian guys did because I am still expected to define stubs and inject them to container explicitly (although on short&amp;amp;easy way)&amp;#160; (issue #1 still exist).&lt;/p&gt;

&lt;p&gt;But, #2 (more important one) is handled with this because test code not depending on the additional dependency wouldn’t crash.&lt;/p&gt;

&lt;p&gt;So, all in one, if you do IoC with Unity go to &lt;a href="http://weblogs.asp.net/rosherove/archive/2008/04/14/creating-a-automockingcontainer-with-microsoft-unity-pretty-darn-simple.aspx" target="_blank"&gt;mentioned Roy blog post&lt;/a&gt; and copy paste the Unity AMC source code for your own usage.&lt;/p&gt;

&lt;h1&gt;Auto mocking container – my way&lt;/h1&gt;

&lt;p&gt;Well, as I presented in &lt;a href="http://blog.vuscode.com/malovicn/archive/2008/06/07/design-for-testability-transparent-and-opaque-dependencies-part-8.aspx"&gt;previous post&lt;/a&gt;, currently the way I am writing and testing my code is that I declare internal constructor accepting the dependencies and perform mock injection without using of any IoC framework.&lt;/p&gt;

&lt;p&gt;But, even for me issues #1 and #2 are not a big problem (I don’t mind declaring mocks and I WANT my test to crash when tested lass change so I have to check out the tests), I can imagine that for some of people this wouldn’t be the case. For them, testing on the simplest possible way with #1 and #2 resolved would be “have to” requirement.&lt;/p&gt;

&lt;p&gt;The good news here is that there is solution for this almost “out of the box” thanks to the design decisions I made in previous posts:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;I would have Facade component (ServiceLocator) encapsulating concrete IoC framework usage &lt;/li&gt;

  &lt;li&gt;Default constructor performs “poor man dependency injection” using the ServiceLocator &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If we think about what the problem really is AMC tries to solve we would come up with something like this: &lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“When IoC container is asked to retrieve a type implementing some interface and that mapping is not defined, return a mocked instance of the interface.” &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And that is exactly what I would do…&lt;/p&gt;

&lt;h2&gt;Modifying ServiceLocator&lt;/h2&gt;

&lt;p&gt;ServiceLocator class is going to support testing mode when instead of IoC container exception throwing (for cases of no type can be retrieved from IoC container for a given interface) ServiceLocator would create a new mocked instance. Something like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;using System;
using Microsoft.Practices.Unity;
using Rhino.Mocks;

namespace Facade
{
    public static class ServiceLocator
    {
        private static readonly MockRepository _mockery 
            = new MockRepository();
        private static readonly UnityContainer _unityContainer
            = new UnityContainer();

        public static bool TestMode { get; set; }

        public static void InjectStub&lt;em&gt;(I instance)
        {
            _unityContainer.RegisterInstance(instance
                , new ContainerControlledLifetimeManager());
        }

        public static T Retrieve&amp;lt;T&amp;gt;;()
        {
            try
            {
                return _unityContainer.Resolve&amp;lt;T&amp;gt;();
            }
            catch (ResolutionFailedException e)
            {
                if (TestMode)
                {
                    return _mockery.DynamicMock&amp;lt;T&amp;gt;();
                }
                throw new InvalidOperationException(“Can&amp;#39;t resolve dependency.”;, e);
            }
        }
    }
}&lt;/em&gt;&lt;/pre&gt;

&lt;p&gt;As you can see service locator now has dependency to Rhino mocks (MockReporsitory class) which is ok IMHO. There is also TestMode new boolean property which represents the way to switch ServiceLocator from production to test mode. Retrieve method now puts IoC Resolve method call inside of try block. In catch block there is conditionalization based&amp;#160; on TestMode value: in case ServiceLocator is in test mode mocked instance is returned and in case ServiceLocator is in production mode Unity exception is been bubbled up.&lt;/p&gt;

&lt;p&gt;And that would be all what we need to do to support custom AMC.&lt;/p&gt;

&lt;h2&gt;&lt;/h2&gt;

&lt;h2&gt;&lt;em&gt;Writing tests using custom AMC&lt;/em&gt;&lt;/h2&gt;

&lt;p&gt;Now when we have the AMC container done, let’s check out how the test from last blog post would look like now with custom AMC used. &lt;/p&gt;

&lt;p&gt;Let add first additional dependency to UserManager constructor so we would have the right use case for AMC (original constructor had only one IUserProvider in which case AMC usage doesn’t have sense)&lt;/p&gt;

&lt;p&gt;So the UserManager class would look after that modification something like this&lt;/p&gt;

&lt;pre class="c-sharp"&gt;    public class UserManager : IUserManager
    {
        private readonly IUserProvider _userProvider;
        private readonly ISomeOtherDependency _someOtherDependency;

        public UserManager()
            : this(ServiceLocator.Retrieve&amp;lt;IUserProvider&amp;gt;(),
                   ServiceLocator.Retrieve&amp;lt;ISomeDependency&amp;gt;()) { }

        internal UserManager(IUserProvider userProvider, ISomeDependency someDependency)
        {
            _userProvider = userProvider;
            _someOtherDependency = someOtherDependency;
        }

        #region IUserManager Members
        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            var userCollection = _userProvider.GetUserCollection();
            var result = 0;
            foreach (var user in userCollection)
            {
                if (user.Name.StartsWith(userName) 
                    &amp;amp;&amp;amp; user.LastActivity &amp;gt; DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
        #endregion
    }&lt;/pre&gt;

&lt;p&gt;Note that constructor now have additional parameter of ISomeDependency type.&lt;/p&gt;

&lt;p&gt;The test similar to the one from last post but this time using the AMC would look like this:&lt;/p&gt;

&lt;pre class="c-sharp"&gt;    [TestFixture]
    public class UserManagerTest
    {
        private MockRepository mockRepository;

        [SetUp]
        public void Test_Init()        
        {
            mockRepository=new MockRepository();
            ServiceLocator.TestMode = true;
        }

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            IUserProvider userProvider = 
                mockRepository.DynamicMock&amp;lt;IUserProvider&amp;gt;();
            ServiceLocator.InjectStub(userProvider);

            using (mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List&amp;lt;User&amp;gt;());
            }
            using (mockRepository.Playback())
            {
                // using public ctor(NO EXPOSED PARAMETERS)
                var userManager = new UserManager();
                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  
    }&lt;/pre&gt;

&lt;p&gt;Couple of key moments here:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;In test init method I switch ServiceLocator to “test mode” –&amp;gt; command him to return mocks for all types not stored in IoC container in the moment of their retrieval request &lt;/li&gt;

  &lt;li&gt;In test method I am explicitly adding to ServiceLocator &lt;u&gt;ONLY &lt;/u&gt;instance of IUSerProvider (which is related to this test) . &lt;/li&gt;

  &lt;li&gt;ISomeDependency parameter is not mentioned anywhere in the test (solution to #1) &lt;/li&gt;

  &lt;li&gt;I am using &lt;u&gt;the default constructor&lt;/u&gt;. That is giving me the solution to #2 which looks very strange on first sight but once one would realize that behind that default constructor is ServiceLocator based poor man dependency injection things get clearer. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Again, I am aware that this approach to AMC is probably unique (I didn’t saw anything like this on the web) but I just choose to do the AMC through component design and not by some AMC framework (although that is perfectly fine choice with me too)&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;Although I like to keep things in my own hands as much as possible, I see a lot of value coming from AMC usage in writing tests for people who like the AMC idea. &lt;/p&gt;

&lt;p&gt;For people not sure “which pill to take” there comes the list of pros and cons I found on the web (&lt;a href="http://weblogs.asp.net/rosherove/archive/2008/04/25/pros-and-cons-and-of-using-an-auto-mocking-container-in-your-tests.aspx"&gt;here&lt;/a&gt; and &lt;a href="http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx"&gt;here&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pros&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Can be easier to maintain and write tests/Can lead to &lt;strong&gt;easier test maintainability&lt;/strong&gt;. &lt;/li&gt;

  &lt;li&gt;Allows easier focus on testing interaction. &lt;/li&gt;

  &lt;li&gt;Automatic testing the services construction via the IoC container. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Cons&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Speed/performance? &lt;/li&gt;

  &lt;li&gt;It could make the &lt;strong&gt;test a little less readable&lt;/strong&gt; in terms of understanding what gets injected and what the actual dependencies are. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h1&gt;What’s next&lt;/h1&gt;

&lt;p&gt;My DFT blog post series stops here because I am getting fed up writing about unit testing and not having fun doing it is a sign for switching gears :) &lt;/p&gt;

&lt;p&gt;I have recently some real world experience on MVP design pattern appliance in real world scenarios so I plan to write couple of posts describing my thoughts on how to solve common problems most of the people face doing MVP (tackling complexity, communication control\page, need for HttpContext in presenter, composite UI communication, Front controller routing&amp;#160; etc) so in case you are doing WebForm classic ASP NET development and you care about testing your UI stay tuned&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Useful links for AutoMockingContainer&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a title="http://blog.eleutian.com/2007/08/05/UsingTheAutoMockingContainer.aspx" href="http://blog.eleutian.com/2007/08/05/UsingTheAutoMockingContainer.aspx"&gt;http://blog.eleutian.com/2007/08/05/UsingTheAutoMockingContainer.aspx&lt;/a&gt; 

  &lt;br /&gt;&lt;a title="http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx" href="http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx"&gt;http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx&lt;/a&gt; 

  &lt;br /&gt;&lt;a title="http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx" href="http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx"&gt;http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AMC custom implementation source code can be found &lt;/strong&gt;&lt;a href="http://cid-e8cc105df7380bc5.skydrive.live.com/self.aspx/Blog.vuscode.com/DFT9.zip"&gt;&lt;strong&gt;here&lt;/strong&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:eabc7986-9f39-4d14-bc75-830dcf6df3b9" style="padding-right:0px;display:inline;padding-left:0px;float:none;padding-bottom:0px;margin:0px;padding-top:0px;"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/AMC" rel="tag"&gt;AMC&lt;/a&gt;,&lt;a href="http://technorati.com/tags/AutoMockingContainer" rel="tag"&gt;AutoMockingContainer&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Unity" rel="tag"&gt;Unity&lt;/a&gt;,&lt;a href="http://technorati.com/tags/TDD" rel="tag"&gt;TDD&lt;/a&gt;,&lt;a href="http://technorati.com/tags/malovic" rel="tag"&gt;malovic&lt;/a&gt;&lt;/div&gt;&lt;img src="http://blog.vuscode.com/aggbug.aspx?PostID=425" width="1" height="1"&gt;&lt;div class="feedflare"&gt;
&lt;a href="http://feeds.feedburner.com/~f/vuscode?a=mAHA14n2"&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=YyK5CEZs"&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=TUVlV8DN"&gt;&lt;img src="http://feeds.feedburner.com/~f/vuscode?i=TUVlV8DN" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vuscode/~4/dO9DGlG1-Bk" 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/2008/06/08/design-for-testability-auto-mocking-container-amc-part-9.aspx</feedburner:origLink></item></channel></rss>
