Month: January 2013

WCF and dependency inversion using Castle Windsor

When you start to work with TDD and other Agile practices the first thing you try to apply almost everywhere in your code is the Dependency Inversion pattern because you want to invert the logic of your dependencies to make your code more testable and maintainable.

In order to accomplish this result I am using Castle Windsor, while before 2013 I was working with Microsoft Unity. I am not going to jump into the conversation “Which Inversion of Control container is better?” because it really depends on what you need to do. For years I was more than satisfied with Unity but recently I started to create complex bootstrappers for my applications and I found Windsor more flexible, that’s it! Nerd smile

How does WCF create a service instance?

First of all, in order to apply dependency inversion inside WCF we need to understand how WCF works and how it creates new service instance. I found this article on MSDN very helpful during my researches: Extending WCF.

So, this is the final result I want to obtain:


When you create a new service in WCF, you can specify the factory that will be in charge of creating the service instance.

This is the code you should use to specify the factory:

   1: <%@ ServiceHost Language="C#"

   2:     Factory="Raf.DependencyInjectionHostFactory"

   3:     Service="Raf.MyService" %>

Now, the factory should start a new instance of our service, or better, should use the ioc container to resolve an instance of that service.

Second step is to create a custom host that will add a new behaviour to our service, the behaviour will call the service locator (I know it’s an anti-pattern …) to inject the dependencies. In my case, Castle Windsor.


   1: public class DependencyInjectionHostFactory : ServiceHostFactory

   2: {

   3:     protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

   4:     {

   5:         // method called when we hit a request to http:// ... youservice.svc

   6:         return new DependencyInjectionHost(serviceType, baseAddresses);

   7:     }

   8: }


   1: public class DependencyInjectionHost : ServiceHost

   2: {

   3:     // omit

   4:     // ...

   5:     protected override void OnOpening()

   6:     {

   7:         // attach the behavior

   8:         Description.Behaviors.Add(new DependencyInjectionServiceBehavior());

   9:         base.OnOpening();

  10:     }

  11: }

Service behavior

   1: public class DependencyInjectionServiceBehavior : IServiceBehavior

   2: {

   3:     #region IServiceBehavior Members


   5:     public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

   6:     {

   7:     }


   9:     public void AddBindingParameters(

  10:         ServiceDescription serviceDescription,

  11:         ServiceHostBase serviceHostBase,

  12:         Collection<ServiceEndpoint> endpoints,

  13:         BindingParameterCollection bindingParameters)

  14:     {

  15:     }



  18:     public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

  19:     {

  20:         foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)

  21:         {

  22:             var cd = cdb as ChannelDispatcher;

  23:             if (cd != null)

  24:             {

  25:                 foreach (EndpointDispatcher ed in cd.Endpoints)

  26:                 {

  27:                     ed.DispatchRuntime.InstanceProvider =

  28:                         new DependencyInjectionInstanceProvider(serviceDescription.ServiceType);

  29:                 }

  30:             }

  31:         }

  32:     }


  34:     #endregion

  35: }

So, the instance provider is able to retrieve a registration for our service using the service locator:

   1: public class DependencyInjectionInstanceProvider : IInstanceProvider

   2: {

   3:     private readonly Type serviceType;


   5:     public DependencyInjectionInstanceProvider(Type serviceType)

   6:     {

   7:         this.serviceType = serviceType;

   8:     }


  10:     public object GetInstance(InstanceContext instanceContext, Message message)

  11:     {

  12:         IServiceLocator serviceLocator = ServiceLocator.Current;


  14:         return serviceLocator.GetInstance(serviceType);

  15:     }


  17:     public void ReleaseInstance(InstanceContext instanceContext, object instance)

  18:     {

  19:         // if you container allows you to destroy instance

  20:         // you can destroy your service instance here

  21:     }


  23:     #endregion

  24: }

That’s it. Of course my container needs to know what is my service registration, and with Windsor I have two options:

   1: // option one, register the interface

   2: Component

   3:     .For<IWriteService>()

   4:     .ImplementedBy<WriteService>()


   6: // option two register the class

   7: Component

   8:     .For<WriteService>()

   9:     .ImplementedBy<WriteService>()

And of course you need to change the markup of your .svc file depending on how you want to resolve the service, with the interface or with the  class type.

Dependency Injection

Now, let’s assume that my service needs an IUnitOfWork contract, how should we do that?

First of all we need to register both types in our container, and with Windsor one of the possible options is this one:

   1: Component.For<IUnitOfWork>()

   2:             .ImplementedBy<UnitOfWork>(),

   3: Component

   4:     .For<ICommandService>()

   5:     .ImplementedBy<CommandService>(),

And my command service is constructed in this way:

   1: public class CommandService : ICommandService

   2: {

   3:     private readonly IUnitOfWork unitOfWork;


   5:     public CommandService(IUnitOfWork unitOfWork)

   6:     {

   7:         this.unitOfWork = unitOfWork;

   8:     }

   9: }

Note for purist of CQRS: I know that a command service should get a command dispatcher injected but for this blog post I guess it would not make things clear enough, so a unit of work or an IRepository would make more sense.

I got lucky this year, no end of the world.

This year has been seriously tough for me and my family, but finally we went beyond it successfully. So I guess it’s time for my first year review and new year proposals.

2012, relocation(s)

In Spring 2012 we moved away from Bermuda after almost 5 years. The relocation has not been easy, after few months in Netherlands I got sick and I had to quit my job and take a long break. Unfortunately I didn’t take a serious break between Bermuda and Netherlands and my body couldn’t afford it. So, we decided to move to Italy and kite surf for a couple of months (which was quite successful and pleasant …) and take a break from any type of technology (phone, mail, web …).

It was a good break and overall I am quite happy I took it, even if it cost us a lot of money, being on vacation and not getting a revenue. But I personally believe that life is one and health and family come before everything else. That’s it.
Btw I also cured my problem and now I am back in shape and ready for my daily activities, which include this blog.

In November we decided to move back to Netherlands and I successfully signed a new contract for a position of Software Architect for Mproof, a Dutch Software House. The environment is really Agile and friendly and this is making me an “happy coder”. Plus I am working remotely with a team in Ukraine, which I recently visited. It was a nice trip and I was able to share some Agile workshops about SOLID and TDD. I am also quite happy seeing new coders embracing Agile without prejudices.

Recently I also attended the XP days (Agile conference) in Netherlands and I had the pleasure to interact with some Europeans coders and architects. I guess I would speak about Agile and NET, next year and the next XP days, not sure about what yet.

Unfortunately I had to quit a lot of extra activities for a while, such as “blog”, “open source”, “studying”, “certifications” and so on … I had some health problems and the laptop was one of my first enemies during these months so I couldn’t interact with technologies for a while until I was fine. My wife was very helpful during this time and we found in the kite surf a good cure for stress.

Overall expectations

Well, if you ask me now, I can easily say that at the beginning of 2012 we were not planning to leave Bermuda yet, especially for the economical crisis around the world. The relocation was a shock for the family because we were almost used to Bermuda were everything is “another world”, so you can imagine the shock after few months of city living. After we left Bermuda we had some plans but sometimes reality is much different and you need to “adapt” your plans to reality.

  • I completed my IASA certification and in my backlog there is my third book.
  • I couldn’t complete the code of my previous books but my readers can now access all my code on TFS 2012.
  • I finally complete my learning process on kite surfing, even if I can’t jump yet, and I found it a really nice and cool sport.
  • We successfully relocated to Netherlands and this was my dream when I was a kid. I also got a new job which it’s quite challenging right now and of course well paid! Hot smile

Plans for 2013

I have few plans for 2013 but I will do my best to accomplish them. First of all learn Dutch, you can easily live in Netherlands without speaking Dutch, but you will never be “part of it” if you know what I mean. Because I am good European citizen I don’t regret to learn a new European language, even if I can say already that Dutch is a pretty damn difficult language to learn. Smile 

Move back to my blog and show a lot of Agile samples, complete my blog migration on WordPress because I am quite disappointed about Subtext roadmap at the moment.

Totally embrace Agile at my current employer.

Kite surf and be back to gym. Write my third book. Plus I have some private plans with my family that I can’t share with you… Smile

The plans over my blog will all be related to my new book, so you will be able to “taste” a little bit of it over my next blog’s posts. I got a free account on TFS 2012 and I am publishing all my projects over there so that anyone of you can simply go there and get the latest version of what’s available.

I am not sure yet, but I would like to re-start to speak at public conferences, I think the XP days would be a good re-start.

For now that’s it!

TDD a WCF service, is it possible?

Right now I am working on a CQRS project, and I am using WCF as my web service technology. In this project I decided to challenge myself and make a full TDD project. The first big problem I found was to simulate a real web server, because I didn’t want to hit a production or QA environment to run my tests.
Second I didn’t want to write any integration test at all, so I had to figure out how to create an in-Process test to run my WCF methods.

Why in-process test? When you write a unit test, you should test a single functionality, and in order to make the test atomic, it should run in-process. It should not involve third party tiers like a database or IIS, otherwise the test won’t be in-process anymore, so it will became an Integration test.

The first idea I came out was to fake the behaviour of IIS, and in order to accomplish this I could easily work with a mock framework like Typemock and mock out the entire IIS infrastructure.

Is this what I really want? Not at all. I don’t want and I don’t need to fake the behaviour of IIS, I need an instance of it because my WCF services are using custom factories and custom behaviours and I need to be sure they are acting in the right way.

So I have created two different type of tests. The first one is pure Unit Test, where I verify the command behaviours:

   1: [TestMethod]

   2: public void AddUsersCommandHandler_ValidCommand_WillPersist()

   3: {

   4:     // arrange

   5:     AddUsersCommand expectedCommand = new AddUsersCommand { UsersStream = expectedStream };

   6:     // service with mocked unit of work

   7:     IServiceCommandHandler<AddUsersCommand> handler = new AddUsersCommandHandler(mockUnit.Object);


   9:     // act

  10:     handler.Handle(expectedCommand);


  12:     // assertions against the command behaviour

  13:     mockUnit

  14:         .Verify(x => x.BeginTransaction(), Times.Once());

  15:     mockUnit

  16:         .Verify(x => x.Save(It.IsAny<User>()));

  17:     mockUnit

  18:         .Verify(x => x.CommitTransaction(), Times.Once());

  19: }

The second one is the (in)famous integration test, where you call the WCF service and test the overall process. Unfortunately for the second step I couldn’t find anything really TDD so I had to figure out by myself a different solution.

IIS Express

Yesterday I spent some time googling around for a solution while I found a nice post from Scott Gu about IIS express. With IIS express we have an in-process IIS server that we can startup or shutdown at any time during the lifecycle of our tests. It provides almost all the functionalities provided by IIS and it also trigger the Application_Start event, something not very well handled by Cassini …

So, first of all I had to figure out how to bootstrap my unit tests to run over a different IIS than the one configured in the web.config.

Piece of cake, first of all I need something that allows me to bootstrap IIS express before my unit test harness starts:

   1: [ClassInitialize]

   2: public static void ClassInitialize(TestContext context)

   3: {

   4:     // create a process for IIS express

   5:     issProcess = new Thread(IssUtility.StartIisExpress) 

   6:                  { 

   7:                     IsBackground = true 

   8:                  };

   9:     // start it

  10:     issProcess.Start();

  11:     // create a new channel factory using the generated URL

  12:     factory = new ChannelFactory<IDomainWriteService>(

  13:        new BasicHttpBinding(), 

  14:        new EndpointAddress("http://localhost:5555/services/DomainWriteService.svc"));

  15: }

Then I need another utility to kill everything when my test harness is done:

   1: [ClassCleanup]

   2: public static void ClassCleanup()

   3: {

   4:     // close the WCF factory

   5:     factory.Close();

   6:     // shutdown IIS express

   7:     IssUtility.TearDownIis();

   8:     issProcess.Abort();

   9: }

At this point I can write any test in the following format:

   1: [TestMethod]

   2: public void ChannelFactory_ReceiveValidCommand_WillExecute()

   3: {

   4:     var expectedCommand = BuildAddUsersCommand();

   5:     service.AddUsers(expectedCommand);

   6: }

I found this technique very useful because we work with TFS on Azure so my Build environment cannot be polluted at all with any third party components or by installing the WCF service under test in the build machine.

In the same way I found very quick to bootstrap IIS express for my tests, honestly they are faster than running on my local IIS 8.

IIS Express utility class

Below is the code I use to initialize IIS express, feel free to use it in your tests and let me know if you come up with a better solution than this one.

   1: namespace xxx

   2: {

   3:     using System.Diagnostics;


   5:     public class IssUtility

   6:     {

   7:         private static Process iisProcess;


   9:         // Start IIS on port 5555

  10:         public static void StartIisExpress()

  11:         {

  12:             var startInfo = new ProcessStartInfo

  13:                 {

  14:                     WindowStyle = ProcessWindowStyle.Normal,

  15:                     ErrorDialog = true,

  16:                     LoadUserProfile = true,

  17:                     CreateNoWindow = false,

  18:                     UseShellExecute = false,

  19:                     Arguments =

  20:                         string.Format("/path:\"{0}\" /port:{1}",

  21:                                         @"your WCF dev path", 5555)

  22:                 };


  24:             var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])

  25:                                     ? startInfo.EnvironmentVariables["programfiles(x86)"]

  26:                                     : startInfo.EnvironmentVariables["programfiles"];


  28:             startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";


  30:             try

  31:             {

  32:                 iisProcess = new Process {StartInfo = startInfo};


  34:                 iisProcess.Start();

  35:                 iisProcess.WaitForExit();

  36:             }

  37:             catch

  38:             {

  39:                 iisProcess.CloseMainWindow();

  40:                 iisProcess.Dispose();

  41:             }

  42:         }


  44:         // kill everything

  45:         public static void TearDownIis()

  46:         {

  47:             iisProcess.CloseMainWindow();

  48:             iisProcess.Dispose();

  49:         }

  50:     }

  51: }