.NET and me Coding dreams since 1998!

1Nov/096

Design for testability – WCF proxies

Recently I spent some time participating in projects involving Silverlight, Prism etc and there are couple of interesting things I’ve came up with during that period which I would like to share with the community in a form of a couple of blog posts showing the “enhancements” I did in our Prism based implementation.

I was thinking a lot where to start and as a result of that I have decided to start with something small but useful. I’ll focus in this blog post on Silverlight, but this simple trick is usable in any other client technology making WCF calls. So, here we go…

How to have testable Silverlight code depending on WCF calls

Why reinventing the wheel?

In order to make sure that trivial thing I’ll be writing about today was not already covered by someone I did my Bing homework and came out with two approaches you might want to check out:

While I find both of them to be perfectly acceptable solution I think they are suboptimal due to different reasons.

In case of first solution (which based on screen cast comments is the way a lot of people do) there is one more layer of abstraction to be maintained.
In typical DDD style application we have DB tables mapped to domain entities which are (usually) flattened in web server layer where the WCF service contracts behave as application level services with client centric shapes and behaviors. With this approach we need another interface with either its own behaviors or just copy pasting the service contract and additional adapter class which delegates the calls to proxy. IMHO, layer of abstraction down –> maintainability level up :)

In case of second solution, my objections are similar to the one I have regarding service locator. Abstracting the “locator” (servicehost) leads to opaque dependencies on a consumer level which are much harder to be unit tested and understood. On top of that, I find this solution also to introduce additional complexity with defining factories, providers etc is IMHO are overkill for simple “TDD enable WCF proxy dependable code”

Duct tape programmer solution

Regardless of how much I disagree with Joel on the value of the duct tape programmer, I couldn’t get away from the fact that my solution compared with other two (full of big patterns and cool code) looks exactly like it is been done by the duct tape programmer – me. :) That’s ok, simplicity is #1 design criteria for me.

In this solution I won’t be using therefore any patterns but instead I would just rely on one hack and one small convention to get quickly testable code which is easier to be maintained and understood (compared to other approaches).

Demoware “WCF proxy being called directly” sample

image So, here’s the setup for today post. We are having application which goal is to show the names of the users having salary greater then $1000.

Client is implemented using Silverlight accessing the user data on a server side by making a WCF service calls.

In order to do that I used vanilla Silverlight solution (didn’t want to use Prism here) consisting of two projects:

  • Web application containing a UserService.svc WCF service and hosting a silverlight app.
  • Silverlight application which has UserService service proxy and MainPage showing the names of users in a ListBox.

 

 

UserService.svc

using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SilverlightApplication.Web
{
    [ServiceContract(Namespace = "http://blog.vuscode.com/200911")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService
    {
        [OperationContract]
        public Collection<User> GetUsers()
        {
            return new Collection() 
            { 
                new User { Id = 1, Name = "Nikola", Salary = 1000 },
                new User { Id = 2, Name = "John", Salary = 2000 },
                new User { Id = 3, Name = "Jane", Salary = 3000 },

            };
        }
    }

    [DataContract]
    public class User
    {
        [DataMember]
        public int Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public decimal Salary { get; set; }
    }
}

Nothing important here: In one file OperationContract defining a method GetUsers returning the collection of users (User DataContratct being defined in the same file)

Let’s move on…

MainPagePresenter? Where’s the MainPageViewModel?

Well, I was surprised that many people I spoke with recently think MVVM is not the only “right” way to do SilverlightWPF development and I tend to disagree with that. While MVVM has its own values (it is also presentation pattern of my choice too) you can do MVC or MVP (both passive view and supervising controller) equally successfully like you can do it in desktop applications (speaking of which, Silverlight for me is desktop app deployed through browser) If you don’t trust me, ask Jeremy. That’s why I ended with some implementation for this

So, in order to spice up this blog post a bit I ended with MVP- like implementation with MainPagePresenter implemented like this

using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;

namespace SilverlightApplication
{
    public class MainPagePresenter
    {
        private FrameworkElement view;
        
        public MainPagePresenter(FrameworkElement view)
        {
            this.view = view;
        }

        public void Init() 
        {
            UserServiceClient proxy = new UserServiceClient();
            proxy.GetUsersCompleted += (sender, e) =>
                                       {
                                           this.view.DataContext = e.Result.Where(p => p.Salary > 1000);
                                       };
            proxy.GetUsersAsync();
        }
    }
}

Constructor here is more interesting because it accepts the instance with type inheriting from FrameworkElement (pretty much most of controls in Silverlight) and stores its pointer to a view filed. In other words, abstraction of a view is being injected into the presenter just instead of the IView I am being smart here and using the FrameworkElement as abstraction  every view (user control implements).

It is the good old demoware type of code you’ve seen on a lot of places with proxy being instantiated in the method body spiced up with cool lambda implementation of async event handler (which any better presenter would use to scare the session attendees) and with a simple linq statement filtering the result set to exclude the rows lower then 1000.

The magic in this code starts when view FrameworkElement.DataContext gets set by the filtered result set. Presenter doesn’t have a clue about what specific control view is but still it is able to set its common property to a value generating desired view behavior.

Wiring  up the view and the presenter

There’s really big religious war on the IT sky regarding who is created first (view or viewmodel presenter) and the allowed level of coupling between them. I have my own take on that to which I would dedicate a separate blog post (it is important subject) but for the sake of this blog post let say that it is perfectlly fine that view is created first and that it has direct reference to presenter.

That’s how the view (MainPage.xaml file) ended being implemented like this

using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {
        MainPagePresenter presenter;

        public MainPage()
        {
            InitializeComponent();
            this.presenter = new MainPagePresenter(this);
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.presenter.Init();
        }
    }
}

As you can see in a page constructor a instance of the presenter was created with a pointer to the page itself being passed to presenter (which if you look up would be held as a presenter field and used in Init method).

Then Loaded event handler is being created (don’t put any UI related code in the constructor because it is not guaranteed that UI would be ready when that line would be executed) and in it presenter.Init() method invoked. In other word, view said to presenter “Please set me up!”

Markup code

Did I tell you how much I like WpfSilverlight? Check the simplicity of the markup code!

    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox
                 Name="listBox1"
                 ItemsSource="{Binding}"
                 DisplayMemberPath="Name" />
    </Grid>

Setting ItemsSource to {Binding} effectively said to control “Bind to your own DataContext” (key moment specific to WPFSL), and DisplayMemeberPath Name value can be read “whatever the collection would be in DataContext, collection item would have a property called Name”

Simple, elegant and powerful!

Runtime experience

image

Wow, so much talk about such a simple thing. Ok, I proved it working

My duct tape based solution

is based on the simplest possible solution I was expecting that WCF supports out of box: IXYZServiceClient interface contracting in abstract way proxy behavior. 

To my surprise I have realized that WCF generated proxy is not creating that interface (IUserServiceClient in this example) so I decided to created in manually.

Doing things WCF team should have already done

I’ve clicked on Show All files icon (to see hidden proxy files) and opened Reference.cs file containing proxy c# code.

image

Then I found UserServiceClient class definition

image

Right click it and pick to extract interface (R# can help with this too)

image

I pick only the members I care to be abstracted (leaving unchecked all of the WCF infrastructure members)

image

and ended with this

image image

Obviously not good solution because next proxy refresh and all this is gone, so there are two problems:

  1. How to preserve interface
  2. How to avoid having manually to add interface implementation to generated ServiceClient class.

In order to solve problem #1, I have created then a folder with the same name as the proxy and drag and drop the interface to that folder. First problem solved!

In order to solve problem #2, I am utilizing the fact that the ServiceClient is generated as partial class so I create in the new folder  another partial UserServiceClient class implementing the IUserServiceClient interface. Here’s how that class look like

namespace SilverlightApplication.UserServiceProxy
{
    public partial class UserServiceClient : IUserServiceClient
    {
    }
}

I hope now you can get the reason why I was a folder with the same name as the proxy –> the namespaces of types and interfaces in that folder are matching out of the box the ones in the proxy class

And here's the solution (for visual learners like me)

image

To summarize the solution:

  • I’ve created the IServiceClient by simple extracting the facade of the proxy client interface
  • I’ve created partial UserServiceClient which is only attaching the interface to proxy
  • Both of files are  not destroyed with proxy regeneration.
  • If the WCF service contract changes over the time, regenerating of new IUserServiceClient is trivial task taking less then 15 seconds.

Duct tape solution at its best! :)

Modifying presenter

using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;

namespace SilverlightApplication
{
    public class MainPagePresenter
    {
        private FrameworkElement view;
        private IUserServiceClient userServiceClient;
        
        public MainPagePresenter(FrameworkElement view, IUserServiceClient userServiceClient)
        {
            this.view = view;
            this.userServiceClient = userServiceClient;
        }

        public void Init() 
        {
            this.userServiceClient.GetUsersCompleted += (sender, e) =>
                                       {
                                           this.view.DataContext = e.Result.Where(p => p.Salary > 1000);
                                       };
            this.userServiceClient.GetUsersAsync();
        }
    }
}

As you can tell I’ve made two changes:

  • added another parameter to the constructor injecting the newly created IUserServiceClient interface
  • Modified Init method to replace proxy instantiation with usage of injected client proxy abstraction.

Modifying the view

Usually I wouldn’t modify the view but instead rely on IoC container to inject the UserServiceClient instance, but in order to keep this post focused I won’t be using IoC here (you’ll see it in one of my future posts showing my Prism enhancements) so I needed to make a simple change in a page constructor

        public MainPage()
        {
            InitializeComponent();
            this.presenter = new MainPagePresenter(this, new UserServiceClient());
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

Nothing special, just added new UserServiceClient() to the parameters being passed to a presenter.

Running the app again

image

Yeap, still works :)

Where’s the unit test?

Well, this blog post is long enough (and it is late enough :)) so I would skip the unit test example this time because it is fairly trivial to be written now when we have interface of the service proxy.

Summary

In this blog post I showed another way how to easy introduce a layer of simple abstraction between the WCF service proxy and the code consuming it.

I find the advantage of my approach VS the two of others in its simplicity and maintainability but again considering I “invented it” that comes as no surprise to me :)

Source code of the end solution can be downloaded from here.

del.icio.us Tags: ,,,
Filed under: Uncategorized 6 Comments
20Oct/095

Say no to ServiceLocator

(Disclaimer: As I stated here, while I find over the time ServiceLocator based code to be a bad practice, I do understand the need for its usage in certain brown-field  scenarios as a way of reducing the risk while introducing the IoC.)

In my previous Nikola’s laws of dependency injection blog post I stated couple of IoC laws based on my experience:

  1. Store in IoC container only services. Do not store any entities.
  2. Any class having more than 3 dependencies should be questioned for SRP violation
  3. Every dependency of the class has to be presented in a transparent manner in a class constructor.
  4. Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies.
  5. IoC container should be explicitly used only in Bootstrapper.
    Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container.

The #5 (“IoC container should be a ghost even in unit tests”) resulted with couple of blog post comments and emails asking for clarification what I mean by that.

In short:

Say no to Service Locator Opaque dependencies!

imageRadenko Zec posted in comment example which with very slight modifications (to reflect better my Law #1) looks like this…

There are 4 projects in the solution used in today blog post:

  1. ClassLibrary containing the two classes where:
    - UserRepository is having dependency on other
    - LoggingService (implementing the ILoggingService)
  2. ConsoleApplication1 simulating the production usage and containing the:
    - bootstrapper class (defining IoC mappings) and the
    - Program.cs (main console file which would execute our functionality
  3. Infrastructure containing my naive implementation of Unity container adapter with the
    - IContainer abstraction of the Unity container,
    - UnityContainerAdapter class implementing the adapter design pattern adapting the UnityContainer to IContainer 
    - UnityContainer service locator class,
  4. TestProject1 containing the unit test for the ClassClibrary1 - UserRepositoryTest

Before diving into the Radenko’s sample implementation let me restate my point by saying that

  • none of the classes using IoC (in this simple example UserRepository) should NOT be aware at all of IoC and
  • UserRepositoryTest should NOT have testfixture setup methods filling the container

Service locator based implementation

As given in Radenko’s comment example Bootstrapper class registers the mappings

namespace ConsoleApplication1
{
    using ClassLibrary1;
    using Infrastructure;

    public static class Bootstraper
    {
        public static void SetUp()
        {
            IContainer cont = UnityContainer.Instance();
            cont.Register<ILoggingService, Loggingservice>();
        }
    }
}

Here’s the simple implementation of that LoggingService (not very important for this blog post but still to be clear)

namespace ClassLibrary1
{
    using System;
    using System.Diagnostics;

    public class LoggingService : ILoggingService
    {
        public void Log(string message)
        {
            Debug.WriteLine(string.Format("LOGGED: {0}.", message));
        }
    }
}

And here’s the class being dependable on that LoggingService

namespace ClassLibrary1
{
    using Infrastructure;

    public class UserRepository
    {
        public void Delete (int userId)
        {
            IContainer cont = UnityContainer.Instance();
            ILoggingService loggingService = cont.Resolve<ILoggingService>();
            loggingService.Log(string.Format("User with id:{0} deleted", userId));
        }
    }
}

So, as you can see in a given example Delete method is implemented like this:

  • get ServiceLocator (singleton instance of the UnityContainerAdapter)
  • using the ServiceLocator retrieve from IoC container component mapped to ILoggingService
  • use that component to log a message.

What is wrong with this code?

  • It violates the Separation of Concerns Single Responsibility Principle  – UserRepository taking care about IoC, instance resolution etc
  • It good example of opaque dependency injection which hides sometime the set of dependencies component has.

    Looks like “not a big deal” but when you face the class with couple of thousands of lines and you have to read them ALL just to get the list and repeat that couple of times, it is a big deal. (Yes, I do agree with you that having that long classes is atrocity of its own kind, but seeing it all the time in my world)

(Couple of more reasons but let’s just continue our journey…)

Here’s how the production usage would look in this example

namespace ConsoleApplication1
{
    using ClassLibrary1;

    class Program
    {
        static void Main(string[] args)
        {
            Bootstraper.SetUp();
            UserRepository userRepository = new UserRepository();
            userRepository.Delete(3);
        }
    }
}

No magic there: code issues a command to bootstrapper to initialize IoC, create a instance of UserRepository and invoke its Delete method.

The last thing left is the example of unit test one might write with this code

namespace TestProject1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using ClassLibrary1;
    using Infrastructure;
    using Rhino.Mocks;

    [TestClass]
    public class UserRepositoryTest
    {
        private ILoggingService loggingService;

        [TestInitialize]
        public void Would_Be_Executed_Before_Every_Test()
        {
            var serviceLocator = UnityContainer.Instance();
            loggingService = MockRepository.GenerateMock<ILoggingService>();
            serviceLocator.Register(loggingService);
        }


        [TestMethod]
        public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
        {
            // arrange
            var userId = 3;
            loggingService.Expect(p => p.Log(string.Empty)).IgnoreArguments();

            // act
            UserRepository userRepository = new UserRepository();
            userRepository.Delete(userId);

            // assert
            this.loggingService.VerifyAllExpectations();
        }
    }
}

This is not a blog post on unit testing so just a short discussion what the test does :

In Test initialization the singleton instance of IoC containe is retrieved. Then an RhinoMock dynamic mock class of ILoggingService is created and then injected into the container. Summarized: we stored something in a container before the test execution, because we know from the source code that it would be used in SUT.

The test itself is very simple:

  • Arrange defines what is the expected behavior of the logging service which is supposed to be caused as a result of SUT activity
  • Act creates an instance of the UserRepository and invokes the delete method
  • Arrange verifies that the expected behavior of the logging service occurred.

Nothing much –> just another example of behavior unit testing.

What is wrong with this unit test?

Well, I wrote them “a few” like this and it works well but with certain pain points which the more test you write the more painful become:

  1. It prevents black box unit testing.

    I tend lately to think about unit tests more as of a functional specifications and due to that I try always to test the class based on defined functional requirements WITHOUT looking in the implementation (to stay as objective as I can). Only once I cover ALL functional cases, I tend to do a quick check of the test coverage and focus on removing the code not being tested (all reqs satisfied and code not used –> potential overkill)
  2. Prevents effective unit testing

    Sooner or later, with this code you end with writing test following the “run the test, get what is missing, add a mapping, run it again, get what is missing, add a line…”  which IMHO ends to be very slow process.
  3. Makes Fixture'SetUp very big and clunky.

    Here we set up one dependency, but imagine hundreds of unit tests with their own many dependencies dig up in the code and how big this section would become…

    In the past I was trying to tackle that by creating special bootstrapper classes filling the IoC container with test infrastructure stubs and with using AutoMockingContainer (still not completely sure about should I do that or not – another blog post) but the end result is that I got more code to be maintained and which is getting broken wevery time production interfaces change etc.

  4. Decreases test readability

    If you want take tests as a sort of functional specification (and you should) pretty often you would want to “read the tests” in order to get what and how the SUT works. Having a bunch of setup code outside of the method being read makes that much harder.

All the right solutions are always simple as possible

In order to comply to law #5 I need to refactor the UserRepository implementation by removing IoC container from it and in order to comply law #3 I need to explicitly enlist in a constructor all of its dependencies.

So, following those two rules I end with this code:

namespace ClassLibrary1
{
    public class UserRepository
    {
        private readonly ILoggingService loggingService;

        public UserRepository(ILoggingService loggingService)
        {
            this.loggingService = loggingService;
        }

        public void Delete (int userId)
        {
            this.loggingService.Log(string.Format("User with id:{0} deleted", userId));
        }
    }
}

As you can see all I did was to transform the ServiceLocator type of code to dependency injection type of code where there is no more SoCSRP violation and where the UserRepository is unaware of IoC (no single line related to it).

For the folks with concerns that this could result with some very long constructors with too many dependencies I suggest checking out Auto Mocking Container and/or:

Law #2 Any class having more than 3 dependencies should be questioned for SRP violation

Let see the unit test for this class

namespace TestProject1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using ClassLibrary1;
    using Rhino.Mocks;

    [TestClass]
    public class UserRepositoryTest
    {
        [TestMethod]
        public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
        {
            // arrange
            var userId = 3;
            
            var loggingService = MockRepository.GenerateMock<ILoggingService>();
            loggingService.Expect(p => p.Log(string.Empty)).IgnoreArguments();
            // act
            UserRepository userRepository = new UserRepository(loggingService);
            userRepository.Delete(userId);
            
            // assert
            loggingService.VerifyAllExpectations();
        }
    }
}

As you can see above:

  • There is no more initialization routine – all of the code related to this test is in one place.
  • Every test initialize only what it needs (no big chunk of initializing union of  of mappings all tests need)
  • While writing the test the C# compiler informs me that the UserRepository needs a logging service. If I don’t provide it test won’t compile.

    That’s how I can avoid looking at the source code in order to get what dependency class has,
  • As for law #5, notice that in my unit test there is NO IoC code at all (even infrastructure component is not referenced anymore).

    IoC has to be for us when needed but also it has to stay away from our work. Full orthogonality. Period.

How the production code looks with new approach?

Almost the same

namespace ConsoleApplication1
{
    using ClassLibrary1;

    using Infrastructure;

    class Program
    {
        static void Main(string[] args)
        {
            Bootstraper.SetUp();
            var unityContainer = UnityContainer.Instance();

            var userRepository = unityContainer.Resolve<UserRepository>();
            userRepository.Delete(3);
        }
    }
}

The main difference is that I’ve used the unity to resolve UserRepository and performs (by that) automatic object graph wire up. It may look like that we ended with the same thing just in other class and that is correct (partially)!

It is correct in a sense that if you think for a second about the real world systems you have many classes chained in cross dependencies in which case it is in your interest to push out from all of them the IoC resolution and let the IoC container of your choice do the auto wire up magic.

It is not correct in a sense that in a most part of your system (usually matching the area you want to test( you what have implict injection and not this explicit. For example, if your CompanyRepository would need a UserRepository (not claiming it has real sense to be done) the CompanyRepository would just have in its constructor IUserRepositoryUserRepository and that’s it.

Conclusion

Reafactoring from service locator to real dependency injection type of code is very easy if not trivial but do require a small “bing!” in your head to just realize it.

After switching to this practice, my tests get much lighter, faster, easier to read and maintain.

Radenko, I hope I answered your question :)

Here’s a sample code I used in today’s blog

Technorati Ознаке: ,,,,
Filed under: Uncategorized 5 Comments
18Apr/093

Prism (CAL) unit testing – How to test Prism (CAL) Event Aggregator using Rhino Mocks

I spent some time recently working with Microsoft Composite Application Guidance (A.K.A. "Prism", “CAL”) and I think it is very good platform for building composite UI by either using WPF or Silverlight.

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.

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.

And that leads us to today’s blog post…

How to test Prism (CAL) EventAggregator based code using Rhino Mocks?

imageSUT I’ll be using today will be as simple as possible to deliver the message.

LoggingService is service which is responsible for handling the logging of system errors in a way that:

  • subscribes to system wide events which are requested to be logged without referencing the event sources
  • decides if event needs to be published (based on severity)
  • if it does, it formats the system event adding the time stamp etc
  • calls the publishing service which is handling the publishing of formatted event

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 dependency injected only a component implementing the IPublishingService.

Subscription to system wide events on a decoupled manner is possible through EventAggregator design pattern  which implementation is in Prism provided through IEventAggregator service.

The LogErrorEvent is an event to which LoggerService would subscribe and which carries the event argument of EventData type containing the ErrorLevel and ErrorMessage data.

Show me the code

Enough of my blabbering (and my English), code will speak for itself much better :)

Sample used in today's blog post can be downloaded here.

LoggingService

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<LogErrorEvent>()
                .Subscribe(this.LogIt);
        }

        private void LogIt(EventData eventData)
        {
            if (eventData.ErrorLevel<=100)
                return;

            var stringBuilder = new StringBuilder();
            stringBuilder
                .AppendFormat("Date:{0}", DateTime.Now)
                .AppendLine()
                .Append(eventData.ErrorMessage)
                .AppendLine();
            this.publishingService.PublishError(stringBuilder.ToString());
        }
    }
}

Nothing fancy there:

  • constructor accepts two parameters which provide to LoggingService access to event aggregator and publishing service through inversion of controls.
  • in constructor injected event aggregator is used for subscribing of LogIt method to LogErrorEvent.
  • LogIt method is private (wouldn’t work in case of Silverlight – but that is sepa rate blog post) and does next things:
    • makes sure that only events with level greater then 100 get published
    • formats the given error message into appropriate format
    • pass the formatted message to publishing service

 

IPublishingService, LogErrorEvent and EventData

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; }
    }
}

No need to waste time commenting this…

Testing the code

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 

Test 1 – How to make sure that event is getting subscribed

        /// 
        /// Shows how to verify that event aggregator subscription occurred.
        ///
        [TestMethod()]
        public void Ctor_Default_WouldSubscribeToLogErrorEvent()
        {
            // arrange
            var publishingServiceStub = MockRepository.GenerateStub<IPublishingService>();
            var eventAggregatorMock = MockRepository.GenerateStub<IEventAggregator>();
            var logErrorEvent = MockRepository.GenerateMock<LogErrorEvent>();

            // event aggregator get event would return mocked log error event 
            eventAggregatorMock.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);
            
            // expect that LogErrorEvent would be subscribed in constructor
            logErrorEvent
                .Expect(p => p.Subscribe(null))
                .Return(null)
                .IgnoreArguments() // we don'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();
        }

The test is using Rhino Mocks AAA syntax introduced in 3.5 version (if you don’t know it, read Rhino Mocks Documentation Wiki excellent documentation).

In Arange section test:

  • defines two stubs for the services being used (stubs because I don’t care to set any expectation related to them in this test)
  • defines the mock of the event which subscription I am about to check
  • stubs the event aggregator behavior so on GetEvent<LoggErrorEvent>() method call would return event mock I created.
  • 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)

In Act section test just constructs the service

In Assert section test triggers verifying of the event log expectations (which in this test were: someone subscribed to this event)

(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)

Test 2a – How to invoke event aggregator in Act test section

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.

This test shows how to invoke event aggregator to publish the desired event which would trigger code being tested,

In case of this example we want to test that not severe errors (error level <= 100) are not getting published.

        /// 
        /// 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<IPublishingService>();
            var eventAggregatorStub = MockRepository.GenerateStub<IEventAggregator>();

            eventAggregatorStub.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);
            
            // expect that publishing service would never be called
            publishingServiceMock
                .Expect(p => p.PublishError(Arg<string>.Is.Anything))
                .Repeat.Never();
            
            // act
            var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
            
            // invoke the event aggregator
            logErrorEvent.Publish(new EventData()
            {
                ErrorLevel = 100,
                ErrorMessage = "Some error message"
            });

           // assert
            publishingServiceMock.VerifyAllExpectations();
        }

In this test, test is having in Arrange section:

  • An instance of the log error event (not the mock of that event like in the case of previous test example)
  • Mock of the publishing service (in previous test we had stub) because that is service we need to check it won’t be called.
  • Stub of the event aggregator with stubbed GetEvent<LogErrorEvent> method
  • An expectation that PublishError method of the publishing service would never be called (regardless of the parameter being sent to that method)

In Act section test is :

  • constructing the logging service injecting the event aggregator stub and mock of publishing service
  • invoking the Publish method on a log error event instance passing the test data (error level == 100 in this test)

In Assert section, we are just triggering checking of expectation defined on mock of the publishing service (no call made to publish error method)

Test 2b – How to invoke event aggregator in Act test section

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 :))

	/// 
        /// 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<IPublishingService>();
            var eventAggregatorStub = MockRepository.GenerateStub<IEventAggregator>();

            eventAggregatorStub.Stub(p => p.GetEvent<LogErrorEvent>()).Return(logErrorEvent);

            publishingServiceMock
                .Expect(p => p.PublishError(Arg<string>.Matches(param => param.Contains("Some error message"))))
                .Repeat.Once();

            // act
            var loggingService = new LoggingService(eventAggregatorStub, publishingServiceMock);
            logErrorEvent.Publish(new EventData()
            {
                ErrorLevel = 101,
                ErrorMessage = "Some error message"
            });
            // assert
            publishingServiceMock.VerifyAllExpectations();
        }

Almost the same sample like previous one just with two small differences:

  • In arrange section, expectation is that the PublishError method would be called once with a method parameter containing “Some error message” string (inline constrains)
  • In act section, event is published with error level >100 to trigger the positive case when publishing service is been triggered

Green is nice :)

image

Conclusion

Thanks to P&P team and community feedback, CALPRISM 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&P!

Filed under: Uncategorized 3 Comments
4Apr/091

Microsoft Unity Auto Mocking Container?


How to build Microsoft Unity Auto Mocking container in less then 20 minutes of work…


I have written before in detail about Auto Mocking Containers 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.


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 Roy Osherove Unity AMC container blog post 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.


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.


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.


The idea is simple:



  • create a class specializing the UnityContainer - “AutoMockingUnityContainer”

  • override UnityContainer “Get” methods

  • wrap in try catch block every “Resolve” call

  • if ResolutionFailedException would occur using reflection find greediest constructor (with the most parameters)

  • if no constructor info available, return a mock

  • try to resolve those parameters by using AMC resolve method

  • recourse until you won’t have complete set of arguments needed (real or mocked instances) for constructing the originally requested instance

Code explaining the above mentioned concepts is even simpler so let cut the chase and  save you from pain caused by reading more text written with “my English” ..




“Show me the code”


Imagine we would have a console application which is giving the answer on the meaning of the life

using System;
using Microsoft.Practices.Unity;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
var user = container.Resolve<User>();
Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
Console.ReadKey();
}
}
}


(Code creates UnityContainer instance and the uses it to retrieve instance of user class which WhatIsTheMeaningOfTheLife method is then shown in console output.)


User class is implemented like this:

namespace ConsoleApplication1
{
public class User
{
private readonly ICompanyManager companyManager;

public User(ICompanyManager companyManager)
{
this.companyManager = companyManager;
}

public int WhatIsTheMeaningOfTheLife()
{
return 42;
}
}
}


(User class constructor accepts ICompanyManager parameter which BTW is totally not used in the method used in console application.)


Although totally irrelevant for this blog post, here’s ICompanyManger class code (just not to have any secrets :)):

namespace ConsoleApplication1
{
public interface ICompanyManager
{
void NotImportantMethod();
}
}

If I would run this code as it is I would be rewarded by the nice Unity ResolutionFailedException


Resolution of the dependency failed, type = "ConsoleApplication1.User", name = "". 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)


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.


AutoMockingUnityContainer


Is just a class looking like this

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("Conflict resolution of type:{0}", t));
return mockingHelper.ConstructInstance(t);
}

}
}
}


As you can see no magic there and it does exactly what everyone would expect:



  • Inherit the UnityContainer

  • Override the Resolve method

  • Adds to that override Try Catch block which in case of ResolutionFailedException exception calls the mockingHelper ConstructInstance method

  • Mocking helper instance is stored in a field and constructed with pointer to current unity container in AMCContainer constructor

MockingHelper class


Is just 90 line long class looking like this:

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 = "UnityAMC.MockingHelper";

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("Mock created - {0}", 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("Auto mocking failed for type:{0}", 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("No available constructors.");
}

if (constructorInfos.Length == 1)
{
return constructorInfos[0];
}

var result = constructorInfos[0];
for (int i = 1; i < constructorInfos.Length; i++)
{
if (constructorInfos[i].GetParameters().Length > result.GetParameters().Length)
{
result = constructorInfos[i];
}
}

return result;
}
#endregion
}
}


GetGreediestConstructor method purpose is to get from a given collection of type constructor info's the one which has the most arguments.


ConstructInstanceMethod does next things:



  • For a given type tries to get greediest constructor

    • If no constructor available on a given type  (ex. in case of interface) it returns dynamic mock.

  • code then iterates through the greediest constructor parameters and tries to resolve each one of them

  • if resolution of any of them fails the procedure goes again just this time ConstructInstanceMethod would go one level deeper in object graph.

And that’s about it…


If I would modify my console app code to use AutoMockingUnityContainer instead of UnityContainer, I would end with code looking like this

using System;
using Microsoft.Practices.Unity;
using UnityAMC;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new AutoMockingUnityContainer();
var user = container.Resolve<User>();
Console.WriteLine(user.WhatIsTheMeaningOfTheLife());
Console.ReadKey();
}
}
}


Which would run just fine…


image


Conclusion


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 … :)


My little code example can be downloaded from here


Technorati Ознаке: ,,,

Filed under: Uncategorized 1 Comment
23Dec/085

Dependency injection in real world

Patrick left a comment on one of my previous blog posts asking a couple of very interesting questions that I’ve been asking myself too:

Is service locator legitimate way of doing IoC?

(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)

Dependency injection primer

Let me start with an example how “real” dependency injection implementation code from my blog post could look like:

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) && user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
    }
}

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  so it can be used  later in a method which performs some kind of business logic.

Key concept here to be noticed is that class have literally no clue where from and how userProvider would get injected.

How DI based unit test looks like?

I’ll use Microsoft Unity and Rhino mocks to write a test for the dependency injection primer.

Here it is:

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<IUserProvider>();
            // injecting to unity container mocked instance of user provider
            this.unityContainer.RegisterInstance(userProvider);
            
            using (this.mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (this.mockRepository.Playback())
            {
                // using IoC container for UserManager construction 
                var userManager = this.unityContainer.Resolve<UserManagerIoC>();
                
                // and then performing tested code 
                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days("X");
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  
    }
}

What I did in that test:

  • I am instantiating UnityContainer in test set up to be used as IoC container.
  • In first line of test  method I am using Rhino mocks to create mock of IUserProvider and then I inject that mock to Unity IoC container
  • In a first line of recording block, I set expectation that empty user collection would be returned
  • In playback block, I get an instance of UserManagerIoC class by using IoC container Resolve factory method. (KEY POINT)
  • IoC container would then:
    • examine the constructor of UserManagerIoC class,
    • see that IUserProvider parameter is requested
    • try to find in IoC container registered service implementing IUserProvider interface
    • mocked instance we injected at the beginning of the test would be found
    • mocked instance would be injected to UserManagerIoC
  • Method would be executed and the expected number of users checked

NOTE #1: You could get away from explicit dependency mocking by using AutoMockingContainer but I decide to do it anyhow in this post in order to increase example readability.

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.

Dependency injection upsides and downsides

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)

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:

  • Brownfield scenarios

    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  currently doing the UserManager um = new UserManager() to become unityContainer.Resolve<UserManager>() (Sith language : “What’s the business value?”) and without that change no DI going to happen.

  • Code monkey scenarios

    Vast majority of developers I know don’t get the IoC, TDD etc, which means that one would spend ton of time answering the

    “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  unit tests at all?”..

    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.

  • “TDD == unit test”

    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”.

    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

  • “Why IoC framework X?”

    ”Why UnityContainer?” “Why not Castle?” “Why not Spring?” “Why not StructureMap?” “On my previous job I worked with XYZ and it is the best…”

 

ServiceLocator based dependency injection

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…

The key points that solution has to achieve are:

  1. Core code implementation has to utilize dependency injection
  2. Code has to be “open for testing” but “close for development”  (yes, I am aware how stupid this might sound and it it stupid thing – details bellow )
  3. DI enabling existing code is not allow to cause any breaking compatibility issues (KIC - “keep it cheap” design principle)
  4. No dependency on any particular IoC framework

Lets take a look at the same primer I’ve done with DI this time implemented using service locator

using System;
using Facade;

namespace Example.UserManager
{
    public class UserManagerSL
    {
        private readonly IUserProvider userProvider;

        public UserManagerSL(): this (ServiceLocator.Retrieve<IUserProvider>())
        {
        }

        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) && user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
    }
}

Main differences (compared to dependency injection primer) are:

  • We still have public parameter less constructor

    That parameter less  constructor uses ServiceLocator to retreive instace of IUserProvider on a same way UnityContainer retrieved it in previous test.

    ServiceLocator is just a Facade wrapper around IoC container encapsulating the type of container and hiding not used features.

    Achieved design goal: “Keep it cheap”

    Achieved design goal: “No dependency on particular IoC framework”

  • 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

  • Constructor taking IUserProvider parameter is now internal.

    The assembly containing UserManagerSL class would contain next attribute

    [assembly: InternalsVisibleTo("UserManager.Test.SL")]

Result of this attribute would be that this constructor would be:

- visible to test assembly containing test methods using UserManagerSL

- not visible to any code outside of that test assembly (none of the “core DEV” would be aware of it)

Achieved design goal: “Open for test, close for development”

Achieved design goal: “Dependency injection used in code”

How ServiceLocator based test looks like?

Here are two examples how the service locator code can be tested..

“White box” service locator test style

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<IUserProvider>();
            ServiceLocator.InjectStub(this.userProvider);
        }

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection_WithSL()
        {
            using (this.mockRepository.Record())
            {
                Expect.Call(this.userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (this.mockRepository.Playback())
            {
                // using internal constructor
                var userManager = new UserManagerSL();
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                Assert.IsTrue(numberOfUsers == 0);
            }
        }
    }
}

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)

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.

Using internal constructor

Second approach is based on the fact that internal constructor is accessible to test assembly which makes test built on this way very simple

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<IUserProvider>();

            using (mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (mockRepository.Playback())
            {
                // using internal constructor
                var userManager = new UserManagerSL(userProvider);
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                Assert.IsTrue(numberOfUsers == 0);
            }
        }
    }
}

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.

Using dependency injection

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.

Check it for yourself:

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollectio_IoC()
        {
            var userProvider = this.mockRepository.DynamicMock<IUserProvider>();
            // injecting to unity container mocked instance of user provider
            ServiceLocator.InjectStub(userProvider);

            using (this.mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (this.mockRepository.Playback())
            {
                // using IoC container for UserManager construction 
                var userManager = ServiceLocator.Retrieve<UserManagerSL>();

                // and then performing tested code 
                int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  

Summary

Most of the blog posts I’ve seen present an ideal “perfect day” situation setup  for writing the test which is not always the case in real world.

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.

Source code for this blog post can be found here.

Filed under: Uncategorized 5 Comments
9Jun/081

Design for testability – Auto Mocking Container (AMC) – Part 9

On my quest to design for testability, I've already covered:

My today’s post would be covering AutoMockingContainer (AMC) in both “standard” and “service locator based” versions

What is auto mocking container (AMC)?

I’ll use the example from original Elutian blog post (where the concept of AMC is first mentioned) where the test setup code looks like this:

[SetUp]
public void Setup()
{
  _service1 = _mocks.CreateMock<IService1>();
  _service2 = _mocks.CreateMock<IService2>();
  _service3 = _mocks.CreateMock<IService3>();
  _serviceWeAreTesting = 
       new DefaultServiceWeAreTesting
            (_service1, _service2, _service3);
}

This example applies transparent dependency injection style described in previous post with a class expose a constructor accepting many interface parameters "(“services”) to which class functionality is dependable on.  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:

  • (PIA) during test creation you would probably feel that it is too much “plumbing” code to be done to support testing
  • (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.

To tackle those two issues, smart people at Elutian combined Rhino mocks and Windsor container to tackle those problems.

Using AMC the same test setup code would look like this:

[SetUp] 
public void Setup() 
{ 
  _mocks = new MockRepository(); 
  _container = new AutoMockingContainer(_mocks); 
  _service = _container.Create&lt;DefaultServiceWeAreTesting&gt;(); 
} 


As you can see, in case of AMC we construct AutoMockingContainer with MockRepository instance thrown as parameter.

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.

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).

so now when we have this initialized writing the test is much simpler and looks like this (taken from the same Elutian blog post)

[Test]
public void DoWork_Always_AsksOtherServices()
{
  using (_mocks.Unordered())
  {
    _container.Get&lt;Service1&gt;().DoWork();
    _container.Get&lt;Service2&gt;().DoWork();
    _container.Get&lt;Service3&gt;().DoWork();
  }
  _mocks.ReplayAll();
  _service.DoWork();
  _mocks.VerifyAll();
}

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.

Obviously:

This is much shorter to be written –> issue #1 is solved.

Even if we would add additional  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  –> issue # 2 resolved

(To get AMC source code which you can compile on your box and use, click here)

Auto mocking container and Unity

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 DFT Unity post), so I did little search for Unity AMC and found out that Roy Osherove implemented it already.

Roy provided in that blog post example how test looks:

[Test]
public void MockTwoDependenciesForAConstructor()
{
	MockRepository mocks = new MockRepository();
	AutoMockingUnityContainer container =
        	new AutoMockingUnityContainer(mocks);

	container.WillReturnAStubFor<ILogger>();
        container.WillReturnAStubFor<IEmailer>();

	using (mocks.Record())
	{   
		//Tell our mock to return true when this method is called
        	container.Resolve<ILogger>().IsLogFileFull();
                LastCall.Return(true);	
	}

	//runner class takes both of these mocks in its constructor
        Runner runner = container.Resolve<Runner>();
        Assert.IsNotNull(runner);
}

Well, although his implementation is VERY cool way of “create mock and inject it to container”  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&easy way)  (issue #1 still exist).

But, #2 (more important one) is handled with this because test code not depending on the additional dependency wouldn’t crash.

So, all in one, if you do IoC with Unity go to mentioned Roy blog post and copy paste the Unity AMC source code for your own usage.

Auto mocking container – my way

Well, as I presented in previous post, 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.

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.

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:

  • I would have Facade component (ServiceLocator) encapsulating concrete IoC framework usage
  • Default constructor performs “poor man dependency injection” using the ServiceLocator

If we think about what the problem really is AMC tries to solve we would come up with something like this:

“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.”

And that is exactly what I would do…

Modifying ServiceLocator

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:

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(I instance)
        {
            _unityContainer.RegisterInstance(instance
                , new ContainerControlledLifetimeManager());
        }

        public static T Retrieve<T>;()
        {
            try
            {
                return _unityContainer.Resolve<T>();
            }
            catch (ResolutionFailedException e)
            {
                if (TestMode)
                {
                    return _mockery.DynamicMock<T>();
                }
                throw new InvalidOperationException(“Can't resolve dependency.”;, e);
            }
        }
    }
}

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  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.

And that would be all what we need to do to support custom AMC.

Writing tests using custom AMC

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.

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)

So the UserManager class would look after that modification something like this

    public class UserManager : IUserManager
    {
        private readonly IUserProvider _userProvider;
        private readonly ISomeOtherDependency _someOtherDependency;

        public UserManager()
            : this(ServiceLocator.Retrieve<IUserProvider>(),
                   ServiceLocator.Retrieve<ISomeDependency>()) { }

        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) 
                    && user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
        #endregion
    }

Note that constructor now have additional parameter of ISomeDependency type.

The test similar to the one from last post but this time using the AMC would look like this:

    [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<IUserProvider>();
            ServiceLocator.InjectStub(userProvider);

            using (mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (mockRepository.Playback())
            {
                // using public ctor(NO EXPOSED PARAMETERS)
                var userManager = new UserManager();
                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  
    }

Couple of key moments here:

  • In test init method I switch ServiceLocator to “test mode” –> command him to return mocks for all types not stored in IoC container in the moment of their retrieval request
  • In test method I am explicitly adding to ServiceLocator ONLY instance of IUSerProvider (which is related to this test) .
  • ISomeDependency parameter is not mentioned anywhere in the test (solution to #1)
  • I am using the default constructor. 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.

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)

Conclusion

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.

For people not sure “which pill to take” there comes the list of pros and cons I found on the web (here and here)

Pros

  1. Can be easier to maintain and write tests/Can lead to easier test maintainability.
  2. Allows easier focus on testing interaction.
  3. Automatic testing the services construction via the IoC container.

Cons

  1. Speed/performance?
  2. It could make the test a little less readable in terms of understanding what gets injected and what the actual dependencies are.

 

What’s next

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 :)

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 controlpage, need for HttpContext in presenter, composite UI communication, Front controller routing  etc) so in case you are doing WebForm classic ASP NET development and you care about testing your UI stay tuned

Useful links for AutoMockingContainer

http://blog.eleutian.com/2007/08/05/UsingTheAutoMockingContainer.aspx

http://www.ayende.com/Blog/archive/2007/06/08/The-Auto-Mocking-Container.aspx

http://blog.eleutian.com/2007/02/23/TestsAutoMockingIoCContainer.aspx

AMC custom implementation source code can be found here

 

Filed under: Uncategorized 1 Comment
8Jun/084

Design for testability – Transparent and opaque dependencies (part 8)

On my quest to design for testability, I've already covered:

(In case you don't know what IoC containers are, I advise you to take a peek at Part 4 of this series first before continuing  with this article.In case you are not familiar with Microsoft Unity IoC framework which I would be using in this post read part 7)

Intro

Before I start, I would like to recommend you to subscribe to Alt.NET mail list where you have daily top notch discussions about various ultra interesting subjects.
One of April subjects was Are Opaque Depencies Bad? (Mockist TDD's effect on design) where you can see that some of very smart people were stating that Opaque dependencies are sometime acceptable compromise because they encapsulate complexity and the component dependency information we get anyhow are not that valuable.

IMHO that is wrong because of the reasons I would state in this post and which can be summarized as:

  • writing tests for components implementing opaque IoC style is much harder
  • transparent IoC helps identifying controls which “do too much” – in general the  one with very big number of dependencies are maybe candidate for investigating if there is SoC violation

Opaque dependencies

In most of code in the same example I was using in previous posts in design for testability series, I was writing code similar to this:

using System;
using System.Collections.Generic;
using Facade;

namespace Example.UserManager
{
    public class UserManager : IUserManager
    {
        #region IUserManager Members
        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IUserProvider userProvider=ServiceLocator.Retrieve<IUserProvider>() ;
            IList<User> userCollection = userProvider.GetUserCollection();
            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.Name.StartsWith(userName) 
                    && user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
        #endregion
    }
}

In first line of my the NumberOfUsersActiveInLast10Days method, an instance of type implementing IUserProvider has been retrieved and then used it in next line to get list of all users.
Once the list of users would be retrieved from DAL provider class, method code iterates and filters out all of the users which name starts with given string and which were active in last 10 days.

As you can see the usage of service locator is “hidden” into the method code and invincible outside of that method.

In other words, if we would check out the code using that method 

using System;
using Example.UserManager;
using Facade;

namespace Driver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            UserManager userManager=new UserManager();
            int activeUserCount = userManager.NumberOfUsersActiveInLast10Days(”DB”);
            Console.WriteLine(activeUserCount);

            Console.ReadKey();
        }
    }
}

we wouldn’t get any clue that UserManager has any dependency on ServiceLocator and UserManagerProvider.

This style of implicit usage of IoC framework where IoC framework is embed directly into the members using it, is called opaque dependency injection.

According to my personal experience opaque style is something looking very appealing to people new to IoC because it is a way of implementing IoC with “nothing changed”, so usually it is considered as “acceptable compromise” :)

Testing the opaque dependencies

Let see why I found this opaque style bad on example of how making test for this NumberOfUsersActiveInLast10Days method would look.

The test I would write would have to verify that for no users in database which have username starting the with given string, program would return zero.

I am sitting in black box testing camp (no testing of private method and looking at the code being tested maximally discouraged)  so I usually start my tests writing the playback code

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            using (mockRepository.Record())
            {
                // no clear idea what to mock here
            }
            using (mockRepository.Playback())
            {
                var userManager = new UserManager();
                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  

Well, as you can see after writing the playback code representing the ways how the code would be used, I don’t have clear idea what I should mock in record section so the test wouldn’t fail.

The only way how I can write the test is to run the test, get error

System.InvalidOperationException: The current type, Example.UserManager.IUserProvider, is an interface and cannot be constructed. Are you missing a type mapping?

then add code to record phase mocking that, run the test again, check out additional error messages etc.

Not  very pleasant and productive way to get the final test result which in case of opaque dependency looks like

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            using (mockRepository.Record())
            {
                var userProvider = mockRepository.DynamicMock<IUserProvider>();
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
                ServiceLocator.InjectStub(userProvider);

            }
            using (mockRepository.Playback())
            {
                var userManager = new UserManager();

                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  

Transparent dependencies

Transparent dependency injection style requires explicit definition of dependencies in class constructor, exposing clearly what are the dependency class has.

UserManager class written in this way would look like this

using System;
using System.Collections.Generic;
using Facade;

namespace Example.UserManager
{
    public class UserManager : IUserManager
    {
        private readonly IUserProvider _userProvider;

        public UserManager():this(ServiceLocator.Retrieve<IUserProvider>())
        { }

        internal UserManager(IUserProvider userProvider)
        {
            _userProvider = userProvider;
        }

        #region IUserManager Members
        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IList<User> userCollection = _userProvider.GetUserCollection();
            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.Name.StartsWith(userName) 
                    && user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
        #endregion
    }
}

If we look at the NumberOfUsersActiveInLast10Days method we would see that ServiceLocator class is not been used nay more there. Method now uses userProvider field without knowing how the _userProvider field is been initialized.

We have also two constructors:

  • Internal constructor accepting the parameter of IUserProvider data type and store its value into the _userProvider field
  • Public default constructor not accepting any parameters but which uses the ServiceLocator to retrieve from IoC container service implementing the IUserProvider interface and then calling internal constructor passing that service to internal constructor parameter

“Dude, this is no transparent dependency…”

Usually examples I was finding on net wouldn’t look like the just given example. The internal constructor would become public and the current default constructor doing poor man dependency injection through ServiceLocator wouldn’t exist at all.

Their rationale is that the UserManager would always be constructed using IoC framework which would automatically perform the injection during the IoC container construction time.

In real enterprise development that is often not true because we could have in existing code base a lot of places doing already doing UserManager  mgr=new UserManager() (constructing without the usage of IoC) so that implicit IoC dependency injection  wouldn’t work for them.I guess also that updating all of the current code just to be able to serve the IoC framework wouldn’t be probably very high on “resource allocation list“ spreadsheet, so we could count on the fact that this “legacy” code would stay like it is now.

What I am doing in my approach is basically switching that implicit IoC dependency injection with explicit one. The major difference here is that I am basing my IoC class design on default constructor and not on some specialized one. That’s why when code construct the class, in both cases (using IoC or new keyword) the result is the same – automatic service resolution and dependency injection. In other words, all this would work with any legacy code using the UserManager class.

Another significant gain (IMHO) from my approach is that I am hiding the complexity from production code (only default constructor exposed) while still having the same IoC concepts in place.

After all, having class design “open for testing but closed for code noise” is the whole point of this DTF blog post series.

“Dude, this is transparent dependency, just it is V2” :)

Testing the transparent dependencies

Once we have our code restructured testing is much more easier and even possible without using the ServiceLocator at all.

Writing the test in this case would show me during the Playback definition that UserManager class have a constructor accepting the IUserProvider class which would lead me to the conclusion what I need to mock in order to have this test done without “run until not complaining” approach I described in opaque test example above.

So first we would add to AssemblyInfo.cs file of UserManager appropriate assembly attribute

[assembly: InternalsVisibleTo(&quot;UserManager.Test&quot;)]

After this User.Test assembly would  get access to UserManager internal constructor above so the test would look like this

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
        {
            IUserProvider userProvider = mockRepository.DynamicMock<IUserProvider>();
            using (mockRepository.Record())
            {
                Expect.Call(userProvider.GetUserCollection())
                    .Return(new List<User>());
            }
            using (mockRepository.Playback())
            {
                var userManager = new UserManager(userProvider);

                int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days(“X”);
                Assert.IsTrue(numberOfUsers == 0);
            }
        }  

Couple of things to note in this example:

  • I am not using ServiceLocator at all for implementing this test.
  • I am using internal UserManager constructor to inject UserProvider mock.
  • While writing the line using the internal constructor I realized (from constructor signature) that I need mocked instance of IUserProvider (first line of the test method)

Conclusion

IMHO, using of transparent dependency significantly simplifies the test making. The approach here I presented (with internal constructor) is variation of standard implementation made to hide the complexity and remove the rope from the hands of TDD unskilled developers. Applying it could enable having a small “TDD core team” of people doing component level design and enabling IoC (with all of the benefits) and all other developers totally unaware of the IoC class design which should reduce training costs and increase IoC adoption chances in organizations not applying it.

What's next?

My next blog post would be on how AutoMockingContainer (AMC) makes testing easier in cases we are using transparent  dependency injection style so in a sense with this blog post makes complete explanation on how to test IoC based components done with transparent dependency injection style

Source code of the examples (opaque and transparent) presented in this post can be found here

Filed under: Uncategorized 4 Comments
18May/084

Design for testability – Microsoft Unity (part 7)

On my quest to design for testability, I've already covered:

(In case you don't know what IoC containers are, I advise you to take a peek at Part 4 of this series first before continuing  with this article)

Microsoft Unity in general

Today's post would be covering how IoC looks like in case of Microsoft Unity, which is developed and maintained by Microsoft Patterns and practices team. Microsoft Unity is currently in version 1.1 and it can be downloaded as part of Enterprise Library 4.0 or as a separate download.

Being Microsoft IoC tool, (beside "evil empire" prefix thing) Unity got an excellent documentation and vibrant CodePlex web site with discussion thread where all the answers can be found. IMHO, Unity is the best documented IoC tool which is the most important reason why I prefer to use it

Like StructureMap, Unity is IoC framework only without any additional DAL and UI parts we can find in Spring and Castle Project. It's size is 140 Kb only (70 Kb unity+70 Kb ObjectBuilder2) so it is very lightweight in both senses.

On similar way Windsor builds on top of MicroKernel, Microsoft Unity IoC is built on top of new ObjectBuilder2 which was rewritten to tackle three major issues original ObjectBuilder had:

  • Attribute only interception model without the option of manual code service locator approach (the only way to work with ObjectBuilder was to decorate members getting DI with special attributes [CreateNew] and [Dependency])
  • lack of configuration based approach where in configuration file container components and services are declared.

Unity now fully supports angle bracket configuration mode and "no configuration" mode (with or without using attribute magic) and this blog post would present both ways of using Unity.

Code solution overview

In this example (as in two previous ones) I am starting where the Part 3  ended - with a solution based on manually implemented setter type of dependency injection with internal setters exposed to test assembly. The solution I would end is the same code as the one in StructureMap post   and Windsor post where all of the internals would be removed and manual dependency injection (DI) would be replaced with service locator (SL) usage. SL would be used in this post also in opaque manner like in previous posts.

My main goal with the end state solution of this blog post is to have as similar as possible end code with the code in previous examples so you could compare the solutions.

Note: Although used in this examples,  using opaque dependencies is not good practice, so please check out my next post in this series where I would present in detail how this example would look using transparent IoC dependency injection style which is the way I prefer. The only reason why I am using opaque dependencies in my previous posts is that I found out explaining IoC concepts to people new to it an uphill battle as soon I show constructor accepting all this interfaces as parameters. So, in this posts I do the same thing I do in reality: selling first SL, DI and IoC on a way easier to sell and the once that is done I am introducing transparent DI, AMC (auto mocking container) etc

Using Microsoft Unity with configuration file

Facade.ServiceLocator

Before proceeding to the example itself, I would do first the same thing I did in castle example: build a separate Facade assembly which would expose ServiceLocator singleton and encapsulate usage of Unity block. The two main reasons why I want to do that are:

  • making code using IoC ignorant on what exact Framework is used and
  • to achieve singleton nature of unity container

So, mentioned Facade class library and ServiceLocator static type in this example would look like this

image

with very simple implementation based on delegating calls to Unity

using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Facade
{
    public static class ServiceLocator
    {
        private static readonly UnityContainer _unityContainer;

        static ServiceLocator()
        {
            _unityContainer = new UnityContainer();
            UnityConfigurationSection section= 
                (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(_unityContainer);            
        }


        public static T Retrieve<T>()
        {
            return _unityContainer.Resolve<T>;();
        }

        public static T Retrieve<T>(string key)
        {
            return _unityContainer.Resolve<T>(key);
        }
    }
}

As you can see from the code above ServiceLocator functionality requires adding a reference to three additional assemblies:

image

 

 

  • Microsoft.Practices.Unity  - Contains UnityContainer definition
  • Microsoft.Practices.Unity.Configuration - Contains the UnityConfigurationSection definition
  • System.configuration - Contains the ConfigurationManager type using for manipulating configuration files

In static constructor of the ServiceLocator type there is Unity IoC container initialization, readout of the Unity configuration section from configuration file and initialization of container based on the mappings defined in configuration file.

Configuration file

Configuration file is very simple (at least for this example where we have single container with only 2 singleton components) and it looks something like this:

  <?xml version="1.0" encoding="utf-8" ?>
  <configuration>
		<configSections>
		  <section name="unity"
				type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,							Microsoft.Practices.Unity.Configuration, Version=1.1.0.0,
	  			Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  		</configSections>
		<unity>
			<typeAliases>
				<!-- Lifetime manager types -->
				<typeAlias alias="singleton"
				  type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
				  Microsoft.Practices.Unity" />
			</typeAliases>
			<containers>
				<container>
					<types>
						<!-- Lifetime managers specified using the type aliases -->
						<type type= "Example.UserManager.IUserManager, UserManager"
							mapTo="Example.UserManager.UserManager, UserManager">
							<lifetime type="singleton" />
						</type>
						<type type= "Example.UserManager.IUserProvider, UserManager"
							mapTo="Example.UserManager.UserProvider, UserManager">
							<lifetime type="singleton" />
						</type>
  					</types>
				</container>
			</containers>
		</unity>
  </configuration>

Pretty self-explanatory  configuration file so I would just highlight here that in it:

  • I defined unity configuration section (notice that the section name is the same one used in constructor code snippet above)
  • In Unity configuration section I defined an alias for singleton container life time manager (which usage is optional but because it makes shorter type lifetime definition I think it is good practice to be used)
  • I defined then in default container singleton mappings (using the defined alias) of the type (interface in this example) and mapTo (type implementing interface)

Another thing deserving brief mentioning here is that my example uses app.config but beside app.config and web.config Unity supports custom configuration files in case you want to keep Unity configuration separated from your main configuration data. (Check out the Unity help file for copy/paste how to code example)

Consuming services

Now, when we saw how Unity IoC is getting populated with appropriate components consuming of those components is very easy. Let's check out how Driver console project would look like in this case:

using System;
using Example.UserManager;
using Facade;

namespace Driver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IUserManager _userManager = ServiceLocator.Retrieve<UserManager>);
            int activeUserCount = _userManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

            Console.ReadKey();
        }
    }
}

Yeah, I said it is very simple... :) All we need to do is to Use ServiceLocator.Retrieve method and pass it as Generic parameter service interface of the component we want to retrieve and that would result with Unity returning instance of the type mapped to that interface in app.config. After that code logic uses that instance on the same way how it would use it if there were no IoC.

(For brevity of blog post I would skip the Provider related IoC code. In case you care, check out the code sample which you can get using the link on the bottom of this post

Attribute magic

If you check out the code of UserManager in configuration example just described you would see next code

        private IUserProvider _userProvider;

        public IUserProvider Provider
        {
            get
            {
                if (_userProvider==null)
                    _userProvider=ServiceLocator.Retrieve<UserProvider>);
                return _userProvider;
            }
            set { _userProvider = value;}
        }

The code inside the UserManager is referring that Provider property which then perform lazy retrieval from ServiceLocator of UserProvider type on opaque SL usage way.

        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IList<User> userCollection= Provider.GetUserCollection(userName);

            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }

Unity gives as an option (not necessary to use) of decorating type members in need of injection with [Dependency] attribute and then Unity do all the plumbing for us. In our little example Provider property would get dependency injection automatically by replacing the Provider code above with something simple as this:

        [Microsoft.Practices.Unity.Dependency]
        public IUserProvider Provider { get; set;}

When Unity container creates instance of UserManager it would scan all of the public members searching for the ones decorated with appropriate attributes and  for each one found appropriate component would be retrieved in IoC container for service equal to member type.

In the concrete case above, when constructing UserManager, Unity would detect DependencyAttribute on provider property, it would search for component implementing the IUserProvider and it would set the property value to retrieved component instance.

Container BuildUp

The whole concept above is based on presumption that UserManager instance would be "constructed" by UnityContainer which during that construction would perform injection of IUserProvider dependency  property.

But in some scenarios we have already constructed UserManager instance without using of the UnityContainer (good old userManager=new UserManager()) and we would still like to set all of the properties marked with Dependency attribute with the container components.

To achieve that, we would add to ServiceLocator type BuildUp method which would encapsulate and delegate to Unity BuildUp method

        public static T BuildUp<T>(T instance)
        {
            return _unityContainer.BuildUp(instance);
        }

All we need to do here is to pass instance of the object containing members decorated with DependencyAttribute and UnityContainer would inject appropriate values (that would be Provider property in this example)

The way to use the build this method is as simple as the method itself. If we would take a look at Main method of Driver.Program type we would see something like this

            // using the build up method
            IUserManager _instanceUserManager = new UserManager();
            _instanceUserManager = ServiceLocator.BuildUp(_instanceUserManager);
            activeUserCount = _instanceUserManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

So, as we see here is instance of UserManager constructed without the using of Unity container and therefore I had to add next line in order to perform manual dependency by calling BuildUp method with instance of user manager passed as parameter.

That would result with Provider property being initialized with a UserProvider instance retrieved from IoC Unity container, in other words the end result would be the same as when we retrieve instance from IoC container.

The purists way of doing dependency injection

Although I personally don't see anything wrong in referencing the Unity assembly in assemblies containing domain/business objects due to its lightweight nature, there is a part of .NET community containing a lot of .NET rock stars not thinking like that (as Roy mention it here). Their biggest concern is that by using DependencyAttribute "infrastructure is leaking to domain space".

To tackle that purist separation concerns, Unity offers a way to achieve the same auto injection functionality without the usage of DependencyAttribute.

In short, to achieve this dependency injection constructor type of dependency injection has to be used which means that the type being injected (UserManager) has to define constructor accepting parameter of Service type (IUserProvider). Unity would then during the UserManager constructor check if any of the constructor parameters is contained in UnityContainer and if it is appropriate value would be injected.

So, after I removed the reference to Microsft.Unity itself from UserManager assembly I have to transform the Provider property to become constructor parameter:

        private readonly IUserProvider _provider;
        public UserManager(IUserProvider provider)
        {
            _provider = provider;            
        }

And that's all in this example where we have single constructor. In case we would have multiple constructors, Unity would use the one accepting the most parameters by default. Only in case that we would have multiple constructors and we would need from Unity not to use the greediest  constructor, we would need to decorate that constructor with [InjectionConstructor]  but IMO this is enough corner case to be discarded and Unity can be evaluated as the IoC framework not violating the SoC principle.

Using Microsoft Unity without configuration file

First of all, I won't repeat all of the thing mentioned already so no reason to panic :-). All of the mentioned things related to how the component is retrieved (attribute decoration, build up, ctor injection etc) stays exactly the same and only the way how container is getting populated is changing because in this example there won't be any configuration file.

This is the way I prefer to do IoC container build up mainly because of two reasons:

  • I prefer c# in favor of xml
  • I don't need to copy XML file to other assemblies (test one primarily)

So, I'll remove the configuration file and as a side effect of that the references to Microsoft.Practices.Unity.Configuration and System.configuration can be removed.

Facade.ServiceLocator modifications

I would also add to ServiceLocator type (beside the existing retreive method):

  • Register method which would accept as generic parameters types service interface and component type
  • InjectStub method which would accept as method parameter already instantiated type instance and which I plan to use in tests to inject the object mock to IoC container on similar way StructureMap does that

ServiceLocator would look like this:

using Microsoft.Practices.Unity;

namespace Facade
{
    public static class ServiceLocator
    {
        private static readonly UnityContainer _unityContainer = new UnityContainer();

        public static void Register<I, T>() where T : I
        {
            _unityContainer.RegisterType<I, T>(new ContainerControlledLifetimeManager());
        }
   
        public static void InjectStub<I>(I instance)
        {
            _unityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager());
        }

        public static T Retrieve<T>()
        {
            return _unityContainer.Resolve<T>();
        }
    }
}

Nothing special here: Register method delegates it's functionality to RegisterType unity container method and InjectStub delegates it's functionality to RegisterInstance method.

The only interesting thing here is the ContainerControlledLifetimeManager instance passed as parameter. Not to go too deep, but if you register type with default constructor on every retrieval Unity would return you new instance. To achieve parity with the configuration file part of the post I needed singleton behavior so I passed as a parameter LifetimeManager which makes sure that the type would be instantiated once per container life time which is effectively the singleton behavior I needed. Another interesting thing to note here is that this type is defined in ObjectBuilder2 assembly so add that to the Facade project references

Introducing Builder class

IMHO, building up the IoC container deserves separate entity which I usually call Builder so in this example Builder class would look something like this:

namespace Driver
{
    public static class Builder
    {
           public static void Init()
           {
               ServiceLocator.Register<IUserManager, UserManager>();
               ServiceLocator.Register<IUserProvider, UserProvider>();
           }
    }
}

So, the builder class effectively replaced the app.config file role defining mappings between services and components in UnityContainer

(Note: In this example, my builder class belongs to Driver application project which is not something I would do always in real world where I would usually prefer to utilize separate interface design pattern (there would be separate post on that too) and have separate assembly containing the Builder type)

Consuming services

Once builder code is in place Driver.Program class would be modified just to call Builder.Init() method before any code would be executed so any code in need of IoC components would retrieve it component

 

using System;
using Example.UserManager;
using Facade;

namespace Driver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Builder.Init();

            IUserManager _userManager = ServiceLocator.Retrieve<IUserManager>();
            int activeUserCount = _userManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

            Console.ReadKey();
        }
    }
}

Yes, it is simple as that.

How to write unit tests with Microsoft Unity?

In my preferred case of having Builder driving the configuration and not the xml configuration file it is very easy. All I need to do is to inject into IoC Unity container mocked instances which would be then used by tested code.

Check out the test:

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers()
        {
            using (mockRepository.Record())
            {
                IUserProvider userProvider = mockRepository.DynamicMock<IUserProvider>();
                Expect.Call(userProvider.GetUserCollection(null))
                    .IgnoreArguments()
                    .Return(new List<User>());
                // injecting to UnityContainer mocked provider instance 
                ServiceLocator.InjectStub(userProvider);
                
            }
            using (mockRepository.Playback()) 
            {
                IUserManager _userManager = new UserManager();
                int count = _userManager.NumberOfUsersActiveInLast10Days("M");
                Assert.IsTrue(count == 0);
            }
        }

 

The only thing to notice here is how using the ServiceLocator.InjectStub method mocked instance is been registered in UnityContainer for purposes of this test execution.

All you need to do is to fill up the container with appropriate mocks/stubs/fakes and run the test

(Note: The test style described here is the one used in case of opaque dependencies which is not something I recommend as best practice. Mu next blog post would show the slightly different way how I write tests while using opaque injection style so be sure to check that out too)

What's next?

Purpose of this DFT blog posts is just to give a How-To quick start on Microsoft Unity so to get more information's on Unity I recommend checking next links:

Source code of the examples (config, attribute, buildup, purist, noconfig) presented in this post can be found here

 

Filed under: Uncategorized 4 Comments
25Feb/082

Design for Testability – Structure map (Part 6)

On my quest to design for testability, I've already covered:

(In case you don't know what Inversion of Control (IoC) containers are, I advise you to take a peek at Part 4 of this series first before continuing  with this article.)

Today's post will cover what IoC looks like when using StructureMap, which was developed (and is maintained) by Jeremy D. Miller, The Shade Tree Developer. In this post, I'm using the current production version (2.0). Once version 2.5 is published, I'll cover it in separate post.

In contrast to Castle Windsor, the StructureMap framework only contains a lightweight IoC container without any additional unrelated parts. You can download the zip file containing StructureMap here. After you unpack the zip file, simply add a reference to "StructureMap.dll" to start using it.

Summary of the changes required by StructureMap

Once again, I will use the same code from Part 3 (manual DI based on internals) and transform it with StructureMap to something very similar to the Windsor example in my previous post. All the internals will be removed and DI injection will be replaced with service locator. Components will pull in their dependencies from a "well-known-object" implementing the Service Locator design pattern.

Something like this:

 image_thumb2

(All of the types are contained in the assembly "UserManager.dll" and their name space is Example.UserManager. The solution also contains a Console application which calls the UserManager method to illustrate how to use the Service Locator in production.)

As you can see, we now have three fully separate types without most of the DI plumbing code and which we locate (when needed) by using the built-in functionality of the Castle Windsor DI framework.

A major difference between the code in this example and the code in the Windsor example is that the StructureMap framework provides a built-in service locator facade type, so you don't need to write the ServiceLocator type yourself.

Another major difference between StructureMap and Castle Windsor is that StructureMap supports attribute-based definition of container components without any configuration files, which can be a major advantage for people who don't want to dig into the bowels of XML configuration files.

StructureMap container configuration

Most of IoC containers are based on same concepts:

  1. using an interface to define an abstraction,
  2. having concrete classes implement that abstraction,
  3. and providing the IoC container with a mapping between the abstractions and their implementations.

In the StructureMap framework, abstractions are called "PluginFamilies" or "PluginTypes" and concrete implementations are called "Plugins" or "PlugedTypes".

There are three different ways of providing StructureMap with the mapping information it needs to perform as an IoC container:

  • Configuration based implementation
  • Attribute based implementation
  • Manual IoC definition

Configuration based implementation of StructureMap

In a configuration based approach, StructureMap works almost the same as Castle Windsor. During the application initialization, StructureMap reads the configuration file (by default the name of configuration file is StructureMap.config) and gets the list of mappings between the interfaces (PluginFamilies) and types that implement the interfaces (Plugins).

The configuration file can be written in a few ways. In my example, I only have a single Plugin (instead of multiple types implementing the same interface). For this type of mapping, the easiest way to write the configuration file is to use the DefaultInstance element.

The configuration file looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<StructureMap>
  <DefaultInstance 
    PluginType= "Example.UserManager.IUserManager, UserManager" 
    PluggedType="Example.UserManager.UserManager,  UserManager"  
    Scope="Singleton"
  />
  <DefaultInstance 
    PluginType ="Example.UserManager.IUserProvider, UserManager" 
    PluggedType="Example.UserManager.UserProvider,  UserManager" 
    Scope="Singleton"
  />
</StructureMap>

It is quite obvious what this configuration file does: Inside the UserManager assembly, there is UserManager type which implements the IUserManager interface. Also, inside the same assembly, there is a UserProvider type which implements the IUserProvider interface. In both cases, we define the scope as Singleton so that StructureMap container will construct the type instances only once.

The very simple DefaultInstance based configuration is not suitable if multiple Plugins implementing the same interface. You can see a more complex (but more powerful) configuration file content with PluginFamily, Plugin and Instance elements in this blog post.

Attribute based implementation

For those (like myself) who are not so keen on writing XML configuration files, StructureMap provides another way of defining IoC container components. Instead of reading values defined in a configuration file, StructureMap performs reflective attribute inspection of the given assemblies and registers all interfaces decorated with [PluginFamilyAttribute] and all the types decorated with [PluggableAttribute].

The end result of either the configuration file or the attribute inspection is the same: StructureMap IoC container gets all the necessary mapping information.

Let's take a quick look at an example of IUserProvider and UserProvider (a link to complete example is at the bottom of this post).

Marking an interface as PluginFamily looks like this:

using System.Collections.Generic;
using StructureMap;

namespace Example.UserManager
{
    [PluginFamily("userProviderService")]
    public interface IUserProvider
    {
        IList<User> GetUserCollection(string userName);
    }

I've decorated IUserProvider with a PluginFamily attribute specifying that the Plugin with key userProviderService is the default implementation.

And this is how the Plugin would be defined:

sing System.Collections.Generic;
using StructureMap;

namespace Example.UserManager
{
    [Pluggable("userProviderService")]
    public class UserProvider : IUserProvider
    {
        public IList<User> GetUserCollection(string userName)
        {
            // return something from DB
        }
    }
}

I've decorated the type which implements the interface (previously defined as PluginFamily) with the Plugin attribute, and provided a concrete lookup key for this implementation. As the key value is the same one used in the definition of the PluginFamily, UserProvider will be instantiated when the StructureMap retreival method is called (unless the key name of another desired plugin were provided to the retrieval method).

Now that we have the appropriate services and types decorated, all we need to do during the application startup is to tell StructureMap which assemblies it should inspect to collect services and concrete types. The code for doing that would look something like this:

            // turn off config file
            StructureMapConfiguration.UseDefaultStructureMapConfigFile=false;
            // collect components from the assembly containing IUserManager
            StructureMapConfiguration.ScanAssemblies()
                .IncludeAssemblyContainingType<IUserManager>();

After disabling the configuration file, I instruct StructureMap to scan the assembly containing IUserManager (which is UserManager in this example). As a result, StructureMap will register all the services and types exactly the same as the configuration file example.

Manual definition

In some cases, we might want to stay away from configuration file but adding attributes is not a viable option (e.g. we don't own the source code or we don't want to introduce a dependency to StructureMap). In these cases, we can take control from StructureMap and perform the appropriate container mappings on our own.

As an example, consider a test method that is supposed to test UserManager (which has a dependency on UserProvider) . My personal preference in writing tests is not to be depend on special - "test" configuration files, so instead I use a helper method for manual registration. The code is similar to this:

        private static void SetUpServiceLocator(I instance)
        {
            // 1. turn off configuration reading
            StructureMapConfiguration.UseDefaultStructureMapConfigFile = false;
            // 2. register a mapping between the service and type into the container 
            StructureMapConfiguration.BuildInstancesOf(I);
            // 3. inject mocked instance
            ObjectFactory.InjectStub(typeof (I), instance);
        }

Method signature defines constraint that "T is I". The input parameter passed to this method is a concrete instance of a type which has to be retrieved later upon any request for "I" service.

In first line of the method StructureMap is instructed not raise an exception if the configuration file is  missing. After that, the service - type mapping is defined. Once the mapping definition is complete, StructureMap is instructed to register the provided instance so that the query to StructureMap for an instance of I will return that instance.

ObjectFactory

Regardless of how the StructureMap configuration is done (configuration file, attributes or manual approach), service location is the same. StructureMap already contains a built-in facade/service locator class, so there is no need to build those on your own (like I did in the Windsor example).

ObjectFactory has two major static methods used in service retrieval:

  • T ObjectFactory.GetInstance<T>();
  • T ObjectFactory.GetNamedInstance<T>(string concreteKey);

As you can tell from signatures, GetInstance method retrieves the default implementation of the service of type T, while GetNamedInstance allows you to pick a specific service implementation.

In this little example, we have a single service implementation so we use the ObjectFactory.GetInstance call:

using System;
using System.Collections.Generic;
using StructureMap;


namespace Example.UserManager
{
    [Pluggable("userManagerService")]
    public class UserManager : IUserManager
    {
        #region IUserManager Members
        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IUserProvider _userProvider
                = ObjectFactory.GetInstance<IUserProvider>();
            IList<User> userCollection
                = _userProvider.GetUserCollection(userName);

            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }
        #endregion
    }
}

 

The only interesting thing in this example (compared to the previous Windsor post) is that I have used StructureMap's built-in SeviceLocator class ObjectFactory.GetInstance<IUserProvider>() to retrieve an instance of  UserProvider implementing the IUserProvider interface. In the Windsor example, I had to build the Service locator on my own.

Note: I am aware of the general concern about having opaque dependencies in this example and I plan to tackle that important question in separate post, so there's no need to criticize me on that (at least not here :-) )

Writing unit tests using StructureMap DI framework

Writing tests with StructureMap is very simple and based on usage of InjectStub method already described in the manual configuration definition section above.

So, to test the business logic in NumberOfUsersActiveInLast10Days, I would need to mock the UserProvider dependency (to prevent DB calls that class does) and then just test the business logic. That would look something like this (same test as in previous blog posts):

         
	[Test]
        public void GetActiveUsers_TestCaseOfZeroUsers()
        {
            using (mockRepository.Record())
            {
                IUserProvider userProvider
                    = mockRepository.DynamicMock();
                Expect.Call(userProvider.GetUserCollection(null))
                    .IgnoreArguments()
                    .Return(new List());

                SetUpServiceLocator(userProvider);
            }
            using (mockRepository.Playback()) 
            {
                IUserManager _userManager = new UserManager();
                int count = _userManager.NumberOfUsersActiveInLast10Days("M");
                Assert.IsTrue(count == 0);
            }
        }

Interesting aspects of this test are:

  • Usage of new explicit Record/Playback model of writing tests using RhinoMocks (previous Windsor post was based on implicit recording model).
  • The first two commands are an example of using RhinoMocks to create a mocked instance of a given interface and to state required behavior for this test (there are no users retrieved from database).
  • The injection of the mock to the StructureMap IoC container is performed by the SetUpServiceLocator method (described above).

What's next?

The purpose of these DFT blog posts is just to give a How-To quick start. To get more information on StructureMap, I recommend the following links:

Source code of the small example presented in this post can be found here

[edited by cbeauvais]

Filed under: Uncategorized 2 Comments
20Feb/085

Design for Testability – Castle Windsor (Part 5)

Pursuing the quest of Design for Testability, we've already covered:

(If you don't know what Dependency Injection (DI) Frameworks/IoC containers are, then I advise you to take a peek at Part 4 of this series first.)

The last episode covered the basic concepts of the DI frameworks, so today's post will present how those concepts are implemented in a DI framework named Castle Windsor.  Castle Windsor is the open source Inversion of Control (IoC) container piece of the Castle Project, which also contains ActiveRecord and MonoRail. There is only one installer for all three parts. Download it from the Castle project web site and install it to your GAC.
After installation, all you need to do to use Windsor is "Add reference..."  to: Castle.Windsor, Castle.Core and Castle.MicroKernel assemblies. 

Summary of the changes caused by Castle Windsor

Today's post will cover the same example I've used in previous DFT blog posts. This DI framework requires some changes to the code structure (although the functionality stays the same).

So, we are starting with this:

With this DI framework, we no longer need the internal properties, replacing them with Castle service locator calls. So the static diagram of the Castle solution looks like this:

image

(All of the types are contained in assembly "Windsor_Example.dll" and their name space is Example.Windsor. The solution also contains a Console application which makes a test call to the UserManager method.)

Summary: We have now three separate types withouth most of the DI plumbing code. Each type will locate the services it needs by using the built-in functionality of Castle Windsor DI framework.

Now, let's dive into the details of how this change is implemented ...

XML configuration

Windsor is a configuration-based DI framework, which means that the application's configuration file has to contain all the settings that the Windsor service locator requires.

Structure of a Windsor configuration file

The Windsor configuration information can be stored either in the default configuration files (App.config, web.config) or in it's own XML configuration file. In either case, it has to include:

  • the definition of the castle Windsor configuration section
  • Inside this section, a collection of components, each of which contains these three elements:
    • id (a key which can be used by the service locator to find an appropriate component to inject)
    • service (which describes the contracted behavior of the component - usually an interface)
    • type (which contains the component that implements the service contract - usually a class that implements the service interface)

The configuration file for our little example is contained in the App.config file of the console application. It looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="castle"
			type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component id="userProviderService"
		service="Example.Windsor.IUserProvider, Windsor_Example"
		type="Example.Windsor.UserProvider, Windsor_Example"/>
      <component id="userManagerService"
		service="Example.Windsor.IUserManager, Windsor_Example"
		type="Example.Windsor.UserManager, Windsor_Example"/>
      <component id="companyManagerService"
        	type="Example.Windsor.CompanyManager, Windsor_Example"/>
    </components>
  </castle>
</configuration>

As you can see, I first define the castle configuration section and then, inside of that section, I have listed all the components contained inside the DI Framework container. The first two components are defined with service and type, while the third component (companyManagerService) is defined only by a type without a service (CompanyManager does not implement any interfaces). Both the type and service attributes contain fully qualified NET type names given in the format "namespace.type, assembly".

Reading the Windsor configuration file

If the Windsor configuration settings are defined in the default application configuration files, it can be accessed like this:

IWindsorContainer _container = new WindsorContainer(new XmlInterpreter());

We create a DI container by passing an instance of the XMLInterpreter to the Windsor container's constructor. This will enable the castle service locator to properly retrieve the desired type.

 

Alternatively, if we wanted to store our castle configuration settings in a separate configuration file (e.g. CastleConfig.xml), it can be accessed like this:

IWindsorContainer _container = new WindsorContainer(new XmlInterpreter("CastleConfig.xml"));

The only difference is that we have to provide a configuration file name to the XmlInterpreter constructor. The content of configuration file is the same regardless of where it is stored.

Different ways to locate a service

There are a few ways to locate a service. This example illustrates 3 of them (you can use intellisense to find others):

	IWindsorContainer _container = new WindsorContainer(new XmlInterpreter());

	IUserManager _userManager;
            
	//generic default service retrieval
	_userManager = _container.Resolve<IUserManager>();

	//service retreival only by given id
	_userManager = (IUserManager)_container.Resolve("userManagerService");

	// generic service retrieval for given id
	_userManager = _container.Resolve<IUserManager>("userManagerServiceA");
	_userManager = _container.Resolve<IUserManager>("userManagerServiceB");

In first example, I retrieve an instance of the user manager by calling the generic form of the container's Resolve method. If multiple components had the given service, the first one would be retrieved.

In the second example, the instance is located for a given id (note that it has to be cast).

In the third example, I retrieve a specific component. This is useful when you have multiple components that implement the same service. We could use this to implement the Strategy pattern.

Service Locator / Facade

From a performance perspective, it is critical that the container initialization occurs only once.

From architecture perspective, we would like to avoid having every solution dependent on Castle Windsor.

We can use the Facade design pattern to solve both problems.

 

This implementation uses a separate assembly which contains a singleton private container instance and some public methods (which delegate their calls to the appropriate container methods). The code looks like this:

using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;

namespace Facade
{
    public static class ServiceLocator
    {
        private static IWindsorContainer _container 
            = new WindsorContainer(new XmlInterpreter());

        public static void Clear()
        {
            _container = new WindsorContainer();
        }

        public static T Resolve<T>()
        {
            return _container.Resolve<T>();
        }

        public static void AddInstance<T>(object instance)
        {
            _container.Kernel.AddComponentInstance<T>(typeof(T), instance);
        }
    }
}

So we see that ServiceLocator is a static class containing the singleton instance of the Windsor container in a private field. The container has been initialized to a set of types defined in a configuration file.

There are three public static methods exposed:

  • Clear - removes all the container components created from the configuration file (this will be used in tests)
  • Resolve<T> - retrieves the instance of desired container component
  • AddInstance<T> - adds a component based on the type instance to the container.

External usage of those methods doesn't require references to the Castle dlls and we get the performance of a singleton container.

Service location

Now that we have explained how service location works, let's take a look at how we would use the Facade ServiceLocator class.

using System;
using System.Collections.Generic;
using Facade;

namespace Example.Windsor
{
    public class UserManager : IUserManager
    {
        #region IUserManager Members

        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IUserProvider _userProvider = ServiceLocator.Resolve<IUserProvider>();

            IList userCollection = _userProvider.GetUserCollection(userName);
            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.LastActivity > DateTime.Now.AddDays(-10))
                {
                    result++;
                }
            }
            return result;
        }

        #endregion
    }
}

If you compare this code with code presented previously in this blog series, you will notice that instead of injecting a dependency into the class through a constructor or setter property, we have now a self-contained method that does not depend on external variables. All this method does is call the "well-known" ServiceLocator type to resolve its dependencies. The rest of the code is exactly the same as in previous posts.

Writing unit tests using Castle Windsor DI framework

The only thing left is to write unit tests with mocks. The approach here is similar to standard mock testing:

  • create a mock instance using Rhino mocks
  • replace the real component with the mocked instance in the container
  • verify the expected behavior

So, if I would like to test the business logic in NumberOfUsersActiveInLast10Days, I would mock the UserProvider dependency (which is reading out the DB for values) and then just test the business logic there. That would look something like this (same test as in previous blog posts):

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers()
        {
            IUserProvider userProvider 
                =  mockRepository.DynamicMock();
            Expect.Call(userProvider.GetUserCollection(null))
                .IgnoreArguments()
                .Return(new List());
            
            //registering the mocked instance as container component 
            ServiceLocator.Clear();
            ServiceLocator.AddInstance(userProvider);

            mockRepository.ReplayAll();

            IUserManager _userManager = new UserManager();
            int count=_userManager.NumberOfUsersActiveInLast10Days("M");
            Assert.IsTrue(count == 0);
        }

 

Creating a mocked instance is pretty obvious. The new thing here is that I am calling the ServiceLocator.Clear method to get rid of the real user provider constructed in the container from configuration values. Once I have cleaned the container, I add the mocked instance. Now the container will return the mocked instance of IUserProvider to all the code asking for it. (The same thing could be done by using the AMC - Auto Mock Container, but I plan to dedicate a separate post on that subject, so I'll use the manual approach here.)

Once the container has been set up, the rest of the test is the same as when you use manual dependency injection.

What next?

The purpose of this blog post is not to go too deep into the details on Castle Windsor; it is more to give a concise overview of concrete steps for using this framework. For more information on Castle Windsor, I recommend these links:

Source code of the example presented in this post can be found here


Quote of the day:

When you encounter seemingly good advice that contradicts other seemingly good advice, ignore them both. - Al Franken

[edited by cbeauvais]

Filed under: Uncategorized 5 Comments