The autistic coder - Andreas Öhlund's blog

world.Publish(new BlogPost());

Today I committed support for running NServiceBus on the Azure cloud to the trunk. Also included is a sample application that demonstrates  how to build NServiceBus solutions for Azure.

Running the sample

  1. To run the sample you have to install the Azure SDK and the Azure tools for Visual Studio. The easiest way to do this is through the  Web Platform Installer. The azure tools are located under “Developer tools” ( If you can’t see them you have to enable them in “options” for the installer)
  2. Once you have tools installed you can get the latest NServiceBus trunk from subversion or download the latest build from our CI. The sample is included in the samples folder
  3. Start up the “AzureService” solution in Visual Studio and hit F5 (NServiceBus defaults to Development Storage if no configuration section is present, more on this later) so you should see the Development. Storage and Development Fabric services start up.

That should be it, the sample should now run in the development fabric on your machine.

Configuration

The Azure queues support is configured using the fluent API

var config = Configure.With()
.SpringBuilder()
.XmlSerializer()
.UnicastBus()
.LoadMessageHandlers()
.AzureQueuesTransport()
.IsTransactional(true)
.PurgeOnStartup(false);


If no configuration section is found NServiceBus will default to your local development storage. To use your personal Azure storage with the sample add the following to the configuration files (web.config, app.config):



<AzureQueueConfig 
AccountName="{Your account name}"
Base64Key="{Base64 key for your account}" />


This configures NServiceBus to create and use queues on your Azure storage account. If you hit F5 again you should see the application start in your local fabric but this time the data is stored on Azure. Cloud Storage Studio is a great tool for managing you storage accounts both locally and on the cloud. The final step is to deploy the entire solution and run it completely on Azure. To do this “publish” the project in Visual Studio and upload the AzureService.cspkg and the ServiceConfiguration.cscfg to your Azure account. Detailed instructions on how to deploy solutions to Azure can be found here.



The sample application is currently running on my own Azure account, please try it out!http://nservicebus-demo.cloudapp.net (And yes my web design skills sucks :)



The sample is doing some simple send/receive and publish/subscribe operations between a WebRole and a WorkerRole. Please take look at the source code for the details.



Considerations when running NServiceBus on Azure



Azure has some limitations that might affect the way you have to design your NServiceBus solutions:




  • Maximum message size is 8kb. Message size has always been a consideration given that MSMQ has a fixed limit of 4 Mb but the 8kb limit will probably cause problems for users that transports large messages on NServiceBus. There are plans to introduce a “data bus” concept to NServiceBus to allow users to transport larger messages.


  • Messages are kept in the Azure Queues for at most 7 days. This shouldn’t be a big problem for normal usage (unless your endpoints are down for more than 7 days that is). But this also means that we can’t use the queues for subscription storage in the same way as we do with MSMQ.


  • All queue names on Azure must be lower case. Complete naming rules here.





What’s next



Right now we support Azure Queues for transporting messages but we can only store subscriptions and sagas using in memory storage. This is of course only acceptable for demos so we are working on adding support for the available storage types that Azure offers . The fact that we have NHibernate implementations for both subscription storage and saga persistence hopefully means that we already support SQL Azure Services but this has not been tested yet. (Ayende has more on this). The next step in this area is to implement support for storing subscriptions and sagas using the Azure Table Storage.



We’re constantly trying to improve NServiceBus both in terms of technology and guidance so stayed tuned for more!

Designing applications that can easily be reconfigured for the different stages in the development lifecycle is important when it comes to shorten the time between development and production. To achieve this we need ways to easily change our applications behavior as it moves through the various stages of software development. Having frameworks that help in this is of course a great start but it’s ultimately up to you as a developer to design and code your application to be lifecycle aware. Udi Dahan has a nice post on the subject that also describes how NServiceBus tries to help in this matter.

Enough talk let’s see an example on how we can combine NServiceBus and StructureMap to create easily reconfigurable applications.

Lifecycle awareness NServiceBus style

In my last post I explained how we could send emails in a “transactional” way using NServiceBus. The solution boiled down to a simple message handler that sends emails through it’s IEmailGateway dependency. Let’s see how we hook up to the built-in profiles of NServiceBus and configure our own dependencies accordingly.

The message handler was implemented as follows:

public class SendEmailMessageHandler : IMessageHandler< SendEmailRequest >
{
private readonly IEmailGateway emailGateway;

public SendEmailMessageHandler(IEmailGateway emailGateway)
{
this.emailGateway = emailGateway;
}

public void Handle(SendEmailRequest message)
{
emailGateway.SendEmail(message.ToAdress,
message.Subject,
message.Body);
}
}


To ease our integration testing we decide to swap out the implementation of IEmailGateway to something that just logs the request to a folder on disk so that we can verify the results either automatically or using our testers.  To do this we configure our endpoint as follows:



public class EndpointConfigWithAwareness : IConfigureThisEndpoint,
As.aServer,
IDontWant.Sagas,
ISpecify.ToRun< DemoEndpoint >,
IWantCustomInitialization,
IHandleProfile< Integration >
{
private static bool IsInProductionMode = true;

public void Init(Configure configure)
{
if (IsInProductionMode)
configure.Configurer.ConfigureComponent< SmtpGateway >(ComponentCallModelEnum.Singlecall);
else
configure.Configurer.ConfigureComponent< FileLoggingOnlyEmailGateway >(ComponentCallModelEnum.Singlecall);
}

public void Init(IConfigureThisEndpoint specifier)
{
IsInProductionMode = false;
}
}


As you can see we implement IHandleProfile<Integration> and uses the call to Init(…) to adjust the mode variable. With this in place we can easily configure the IEmailGateway dependency accordingly. So now when we start the NServiceBus in integration mode , NServiceBus.Host.exe /integration, our emails will be logged to disk instead of being sent to the real SMTP-server. 



Lifecycle awareness vNext



As you can imagine this solution gets kind of ugly when you have more dependencies and more profiles.  As a nice “coincidence” my container of choice, StructureMap, also has the concept of profiles. Please read Chad Myers post for an in-depth explanation. Let’s modify our configuration to combine the both:



public class EndpointConfigUsingStructuremap : IConfigureThisEndpoint,
As.aServer,
ISpecify.ContainerTypeToUse< StructureMapObjectBuilder >,
IDontWant.Sagas,
ISpecify.ToRun< DemoEndpoint >,
IHandleProfile< Integration >
{
private static readonly string IntegrationProfile = typeof (Integration).Name;

public EndpointConfigUsingStructuremap()
{
ObjectFactory.Configure(x =>
{
x.ForRequestedType< IEmailGateway>()
.TheDefaultIsConcreteType< SmtpGateway >();

//setup the alterations for the integration profile
x.CreateProfile(IntegrationProfile)
.For< IEmailgateway >()
.UseConcreteType< FileLoggingEmailGateway >();
});
}

public void Init(IConfigureThisEndpoint specifier)
{
//switch profile to "integration"
ObjectFactory.Profile = IntegrationProfile;
}
}


The code above starts with configuring NServiceBus to use StructureMap as the container. Then we move on to configure all our components using the StructureMap API. Using “CreateProfile” we creates a “Integration” profile where we configure the special version of IEmailGateway to use when running in that profile. With all this setup it’s straight forward to use the NServiceBus profile to activate the correct StructureMap profile. 



Conclusion



Building software that is easily configurable for different purposes is becoming increasingly important to enable rapid development and tight release cycles. To succeed make sure to pick frameworks that enables you to be lifecycle aware but in the end it’s up to you to “connect the dots”.



The source code an a fully working sample of all this can be found here.

Inconsistency problems in your application often occur when you are using technologies that are non transactional. Sending emails using SMTP is one example where there is no “rollback” in case something goes wrong. I want to talk about how asynchronous messaging in general and NServiceBus in specific can help you solve your inconsistency problems with minimal effort.

Let examine a common situation where a user has signed up for some service that you provide and you need to create the account and send a confirmation email to the user. The code would look something along these lines:

  
private IRepository repository;
private IEmailGateway emailGateway;

public void CreateUser(string userName,string password)
{
using(var transaction = new TransactionScope())
{
var user = new User
{
UserName = userName,
Password = password
};

repository.Save(user);

emailGateway.SendEmail(userName,
"Account created",
"Please click the following link to activate account: " +
"http://mysite/confirm&id=" + user.Id);


transaction.Complete();
}
}


Where the IEmailGateway interface is implemented like this:



  
public class SmtpGateway:IEmailGateway
{
private readonly string host;
private readonly string fromAdress;

public SmtpGateway(string host, string fromAdress)
{
this.host = host;
this.fromAdress = fromAdress;
}

public void SendEmail(string toAdress, string subject, string body)
{
var smtpHost = new SmtpClient(host);

smtpHost.Send(fromAdress,toAdress,subject,body);
}
}


At a first glance this code looks ok but the fact that SmtpClient doesn’t support transactions means that if our database call rolls back we’ll send the email without saving the user to our database. This inconsistency will result in users getting confirmation emails without being able to login. Inconsistency bugs is very painful to debug and usually only shows up when the system is under heavy load so they should be avoided at all costs. It’s also obvious that the duration of the synchronous call to the SMTP – server is a direct factor of the total call time and it’s probably just a matter of time before the performance police will come knocking on our door. Further our availability will now have to factor in the availability of the SMTP – server which will make it much harder to achieve high availability. I’ll save the in depth explanation of the availability aspects for a future post so let’s move on to see how we can solve our inconsistency problem by adding pinch of asynchronous messaging.



NServiceBus to the rescue



In order to be consistent we need to wrap the SMTP-call with something that supports transactions. Let’s accomplish that using NServiceBus combined with it’s MSMQ-transport to send a SendEmailRequest instead of actually calling the SMTP-server. The fact that MSMQ supports transactions means that if either the database call to save the user or the call to send the message fails nothing will be committed and we will still be in a consistent state. The modified code looks like this:



  
private readonly IRepository repository;
private readonly IBus bus;

public void CreateUser(string userName, string password)
{
using (var transaction = new TransactionScope())
{
var user = new User
{
UserName = userName,
Password = password
};

repository.Save(user);

var emailRequest = new SendEmailRequest
{
ToAdress = userName,
Subject = "Account created",
Body = "Please click the following link to activate account: " +
"http://mysite/confirm&id=" + user.Id
};

bus.Send(emailRequest);


transaction.Complete();
}
}


As you can see the code is almost identical as before with the important difference in that we’re now sending our email using a durable asynchronous call.



To process the message, on the same server or on a different server, we just implement a message handler for the SendEmailRequest message and host that handler using the generic host that ships with NServiceBus:



  
public class SendEmailMessageHandler : IMessageHandler
{
private readonly IEmailGateway emailGateway;

public SendEmailMessageHandler(IEmailGateway emailGateway)
{
this.emailGateway = emailGateway;
}

public void Handle(SendEmailRequest message)
{
emailGateway.SendEmail(message.ToAdress,
message.Subject,
message.Body);
}
}


If the message handler fails to process the message after the configured number of retries the message will be moved to an error queue where the administrator need to decide what needs to be done in order to resolve the issue.



Conclusion



With a minimal change to our original code we can now guarantee consistency in our application. This setup will also be more testable because we only have to worry about stubbing out the SMTP-server when we are testing the message handler. The fact that we no longer have to wait for the SMTP– server will shorten our call times and boost performance. As a final benefit our application can now function with out the actual SMTP-server being up and running.  This means that our availability is no longer limited by the availability of the SMTP-server.

 

The packaging of NServiceBus 2.0 has been slightly changes compared to 1.9 The reason for this is that the merged NServiceBus.dll started to get to big. While we still strive to keep the number of assemblies down we decided that a split was necessary.

NServiceBus 2.0 will ship the following assemblies:

NServiceBus.dll

Contains only the interfaces and classes that enables you to implement your business logic. This means message handlers sagas, classes with a dependency to the IBus interface etc. This is essentially a lightweight assembly containing the public Api of NServiceBus

NServiceBus.Core.dll

This assembly contains all the core parts of NServiceBus, transports, subscriptions storages, serializes, etc. Any projects that hosts NServiceBus endpoints needs to reference this assembly. NServiceBus and NServiceBus.Core are the only mandatory assemblies so if you are providing your own hosting solution these are the only things you have to reference. (most likely if you are hosting NServiceBus within a asp.net web application)

NServiceBus.Host.exe

NServiceBus 2.0 comes with a new generic host that will take care of hosting your business logic in a flexible way. (Based on topshelf). Justin Ramel has great post on how to use the host

Additional Containers

2.0 will ship with Spring.Net as the default container. If you prefer to use one of the other supported containers, AutoFac, StructureMap, Windsor and Unity you have to reference the NServiceBus.ObjectBuilder.[Name of Container].dll that ships with NServiceBus. We also supply the versions of the actual containers that NServiceBus is compiled against. If you prefer you own version just reference the specific version and assembly redirect accordingly.

The current trunk contains the above packaging and should hopefully be quite stable as we are closing in on the release of NServiceBus 2.0.

Team City has a killer feature called remote run. This gives you the ability to test your changes on the build server before actually committing anything.

Why is this needed, you might ask? 

Let me try to explain with an example. I’ve recently committed some features to NServiceBus where the tests where using Sqlite for in memory testing of NHibernate mappings. The coding went smooth and all test where green “on my machine”. I’ve danced the checkin dance and finally committed the changes.

What do you think happened?

Well the “it works on my machine” devil paid me a visit and made sure that the Continuous Integration choked with a classic “Bad Image Format” exception. It turns out that the build agent over at http://teamcity.codebetter.com is 64-bit and that caused the NUnit test runner to fail because I’ve compiled against the x86 version of Sqllite. But before I’ve got this fixed I had caused 10 failed builds, I don’t have a x64 machine so I had to do trial and error debugging. And trust me repeatedly failing the build is a great way to piss off your fellow developers. If I had been using the “personal build” feature before I committed  this wouldn't have happened.

To start using this feature do the following:

  1. Download the Team City Visual Studio plug in (login to your Team City server and click on “My Settings & Tools”)
  2. Download the CollabNet Subversion client and install it
  3. Open visual studio and
    1. Login to Team City (from the “Team City” menu)
    2. Click on “Remote run”
    3. Make sure subversion support is enabled (see picture below)

personal_build

That should be it. Another great “move” added to my check in dance!

Thanks to Tuna Toksoz for helping me with the Sqlite issue and reminding me of the “personal build” feature!

I've just committed support for StructureMap to the NServiceBus trunk so if you are using NSB and prefer StructureMap as your IoC-Container you can get the latest NSB build from teamcity.codebetter.com (thanks Udi for trusting me as a committer)

To configure NSB to use StructureMap use the following syntax:

var bus = Configure.With()


   .StructureMapBuilder()


   .MsmqSubscriptionStorage()


   .XmlSerializer()


   .MsmqTransport()


       .IsTransactional(true)


       .PurgeOnStartup(false)


   .UnicastBus()


       .ImpersonateSender(false)


   .CreateBus()


   .Start();



If you are using an explicit instance of the container it can be passed to the builder like this:




var container = new Container();


 


var bus = Configure.With()


   .StructureMapBuilder(container)


   ...



The bus itself is added to the container by NSB so to get access to is in your code just add a dependency for it the usual way:




public class ClassThatNeedsAccessToTheBus


{


    private readonly IBus bus;


 


    public ClassThatNeedsAccessToTheBus(IBus bus)


    {


        this.bus = bus;


    }


    public void PerformSomeLogic()


    {


        bus.Publish(new WhatEverEvent());


    }


}



And to fill your message handlers with your own dependencies just configure them in SM and add them as constructor or setter dependencies :




public class MyMessageHandler:IMessageHandler<WhatEverEvent>


{


    private IRepository repository;


 


    public MyMessageHandler(IRepository repository)


    {


        this.repository = repository;


    }


 


    public void Handle(WhatEverEvent message)


    {


        repository.Save(message);


    }


}





Edit: You can also configure dependencies using NServiceBus own syntax , more on that here.



If you have any troubles, suggestions etc. let me know directly or post them to the NSB group.

In this post I will demonstrate a way to automatically manage a UnitOfWork (UoW) for Windows Communication Foundation (WCF) service requests. This is the equivalent of “Session per request” that is popular for Web applications. The reason for all this is to move transaction management out of user code resulting in cleaner and more maintainable applications.

The semantics of my UoW is the following, for each request to my WCF service:

    1. Create a new UoW and initialize it
    2. Cache the UoW in StructureMap for the duration of the request
    3. Commit and dispose the UoW when the request finishes
    4. Rollback the UoW if the service throws an exception

My interface for the UoW looks like this:

   1:  public interface IUnitOfWork : IDisposable


   2:  {


   3:      void Initialize();


   4:      void Commit();


   5:      void Rollback();


   6:  }



 


To do all this we need the following infrastructure.





    1. Basic StructureMap integration for WCF


    2. A way to cache objects for the duration of the service call


    3. Integration between the cache StructureMap


    4. Some hooks in WCF to allow us the Initialize and commit the UoW


    5. Another hook to detect exceptions and rollback the UoW




Let’s taka a closer look at how we can’t implement all this.



Basic StructureMap integration for WCF



This is a solved problem so I wont go into the details (Jimmy Bogard has an excellent post on the subject). Basically this means creating a “ServiceHostFactory” which in the end allows us to specify our own “instance provider”. Using this provider we can use StructureMap to instantiate the reuested instances.



Building a WCF per request cache



To enable caching I decided to cache objects in the WCF InstanceContext. The instance context is isolated for each service instance. This means that we must make sure that WCF creates a new Instance for each call (the default is one Instance per session). This is easily done by adding the following to our service implementations:





   1:  [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]



Ok, but how do we cache stuff in the InstanceContext? Unfortunately WCF doesn't provide any collection like HttpRequest.Current.Items so we have to use the extensibility hooks in WCF to solve the problem. In this case we add our own Instance extension that can handle the caching for us. This is done by creating  a class that implements IExtension<InstanceContext>. The implementation looks like this:





   1:  public class WCFContextCacheExtension : IExtension<InstanceContext>


   2:  {


   3:      private MainObjectCache cache;


   4:   


   5:      public IObjectCache Cache


   6:      {


   7:          get { return cache; }


   8:      }


   9:   


  10:      public static WCFContextCacheExtension Current


  11:      {


  12:   


  13:          get


  14:          {


  15:              return OperationContext.Current.


  16:                  InstanceContext.Extensions.Find<WCFContextCacheExtension>();


  17:          }


  18:   


  19:      }


  20:      public void Attach(InstanceContext owner)


  21:      {


  22:          cache = new MainObjectCache();


  23:      }


  24:   


  25:      public void Detach(InstanceContext owner)


  26:      {


  27:   


  28:      }


  29:  }



Note that I’m using the MainObjectCache from StructureMap as the store for my cached objects, the reason for this will be explained when we take a look at how this can be integrated with StructureMap. I’ve also added a convenience method that finds the extension from the InstanceContext. But how do we make sure that our extension is added to every new Instance?



My approach is to implement a “InstanceContextInitializer” which is added to the dispatch runtime. This is accomplished with this modification to my StructureMap WCF integration:





   1:  ed.DispatchRuntime


   2:     .InstanceContextInitializers


   3:        .Add(new InstanceContextCacheInitializer()); 



The implementation of the InstaceContextInitializer is trivial:





   1:  public class InstanceContextCacheInitializer : IInstanceContextInitializer


   2:  {


   3:      public void Initialize(InstanceContext instanceContext, Message message)


   4:      {


   5:          instanceContext.Extensions.Add(new WCFContextCacheExtension());


   6:      } 


   7:  }



Ok, now that we have a way to cache objects in the InstanceContext lets see how we can integrate this with the StructureMap way of caching instances .



A WCFInstanceContextCache for StructureMap



Extending StructureMap with a custom caching solution is done by implementing your own “lifecycle”. (Here is an indepth discussion of scoping in StructureMap.)



In this case our custom lifecycle would look like this:





   1:  public class WCFInstanceContextLifecycle : ILifecycle


   2:  {


   3:      public void EjectAll()


   4:      {


   5:          FindCache().DisposeAndClear();


   6:      }


   7:   


   8:      public IObjectCache FindCache()


   9:      {


  10:          return  WCFContextCacheExtension.Current.Cache;


  11:      }


  12:  }



As you can see StructureMap requires our cache to implement the IObjectCache interface hence the use of MainObjectCache above. Noting magic here we just fetch the cache from our InstanceContext extension and let StructureMap do the rest.



The will enable us to configure StructureMap like this in order to cache objects for the duration of a service call:





   1:  x.ForRequestedType<IUnitOfWork>()


   2:       .LifecycleIs(new WCFInstanceContextLifecycle())


   3:       .AddConcreteType<TestUnitOfWork>();



Now that we have a way to cache our UoW for the duration of each service call we can move on to making sure that the UoW is initialized and committed automatically for each request.



How to manage the UoW on a Per request basis



To enable us to automatically initialize and commit our UoW we need a way to hook up to the WCF call pipeline. This is done by adding a custom IDispatchMessageInspector (a deeper explanation of MessageInspectors is found here).



To enable us to add message inspectors easily I've added the following feature to my StructureMap WCF integration:





   1:  foreach (var messageInspector in container.GetAllInstances<IDispatchMessageInspector>())


   2:  {


   3:      ed.DispatchRuntime.MessageInspectors.Add(messageInspector);


   4:  }



This gives me an easy way to add MessageInspectors just by configuring them in StructureMap.





   1:  x.ForRequestedType<IDispatchMessageInspector>()


   2:      .AddConcreteType<UnitOfWorkMessageInspector>();



 



With this in place it’s easy to implement my own “UnitOfWorkMessageInspector” that hooks up to WCF and performs the work. This looks like this:





   1:  public class UnitOfWorkMessageInspector: IDispatchMessageInspector


   2:  {


   3:      private readonly IContainer container;


   4:   


   5:      public UnitOfWorkMessageInspector(IContainer container)


   6:      {


   7:          this.container = container;


   8:      }


   9:   


  10:      public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)


  11:      {


  12:          var unitOfWork = container.GetInstance<IUnitOfWork>();


  13:   


  14:          Debug.WriteLine("Before invoke");


  15:          unitOfWork.Initialize();


  16:   


  17:          return null;


  18:      }


  19:   


  20:      public void BeforeSendReply(ref Message reply, object correlationState)


  21:      {


  22:          var unitOfWork = container.GetInstance<IUnitOfWork>();


  23:   


  24:          Debug.WriteLine("After invoke");


  25:          unitOfWork.Commit();


  26:          unitOfWork.Dispose();


  27:      }


  28:  }



As you can see we Initialize, Commit and Dispose the UoW for each “Message” going in and out of our service.



Notes:




  • BeforeSend reply will still be invoked even if the operation is “OneWay”.


  • As you can see we always commits, this works because the implementations of IUnitOfWork is required to always start a new transaction after commit and rollback. This is to allow user code to perform manual commits and rollback. This feature is also required to enable other errorhandlers to update application state if needed. (more on this below)



Ok, so far so good. Lets look at the final piece of the puzzle. The rollback…



Rollback the UoW if the service call throws an exception



By now you’ll probably guess how this will be done:) WCF is extensible beyond belief. First we add some more code that allows us to autoregister WCF Errorhandlers through StructureMap.





   1:  foreach (var errorHandler in container.GetAllInstances<IErrorHandler>())


   2:  {


   3:      cd.ErrorHandlers.Add(errorHandler);


   4:  }



With this in place we can configure a custom “UnitOfWorkErrorHandler” that can perform the rollback in case of an exception. The fact that we are resolving the errorhandlers using StructureMap means that we can have the container itself injected into them if necessary.





   1:  public class UnitOfWorkErrorHandler : IErrorHandler


   2:  {


   3:      private readonly IContainer container;


   4:   


   5:   


   6:      public UnitOfWorkErrorHandler(IContainer container)


   7:      {


   8:          this.container = container;


   9:      }


  10:   


  11:      public void ProvideFault(Exception error, MessageVersion version, ref Message fault)


  12:      {


  13:          var uow = container.GetInstance<IUnitOfWork>();


  14:   


  15:          Debug.WriteLine("Rolling back UoW");


  16:   


  17:          uow.Rollback();


  18:      }


  19:   


  20:      public bool HandleError(Exception error)


  21:      {


  22:          return false;


  23:      }


  24:  }



But why are you not injecting the IUnitOfWork directly?



The reason for this is that there is no ongoing call when the error handler is instantiated so the cache wouldn't work (We are storing the cache in the active service instance remember). The workaround would be to add some kind of “lazy dependency” feature to StructureMap that would instantiate our UoW the first time it’s accessed. But until then will just use the container directly.



The fact that a new transaction is started after rollback enables the other errorhandlers to perform custom business logic that requires an active transaction eg. logging to a database, publishing events to an service bus etc. ( remember that the  “new UoW transaction” is going to be committed by the message inspector above)



Summary



Phew, we are finally done. WCF and StructureMap is really easy to extend. There is a lot of extensions required for this to work but I like the fact that each extensions does its thing and thereby adhering to Single Responsibility Principle. Having the infrastructure managing your UoW is a great way to keep your code clean and minimizes the risk of “forgetting” transaction management.



Resources



The code for the StructureMap WCF Integration can be found here.



A test that shows the configuration and usage of the UoW is here



And the code for the WCF UoW is here



Jimmy Bogard has written a post about this (but it turned out to have some threading problems but It got me stared down the right path)



Donald Belcham at igloocoder.com has posted some info on the subject



AltOxite has a great UoW implementation for Fluent NHibernate that I have shamelessly copied :)



As always comment, suggestions etc is most welcome!