Friday, June 10, 2011

Starting up with NServiceBus

After many years with a inhouse made API on top of MSMQ, its time to evaluate other frameworks that gives us more out of the box.

NServiceBus looks like a great candidate.

  • Easy install

  • Extensible

  • Strongly typed messages using generics

  • Support for unit testing


The first problem was to use the StructureMap container in a strong name solution. The NServiceBus.ObjectBuilder.StructureMap262.dll extension have no stong name so I had to decompile and assemble it again with a keypair.

This is done using ildasm/ilasm.

sn -k test.snk

ildasm NServiceBus.ObjectBuilder.StructureMap262.dll /out=NServiceBus.ObjectBuilder.StructureMap262.il

ilasm NServiceBus.ObjectBuilder.StructureMap262.il /dll /key=test.snk /output=NServiceBus.ObjectBuilder.StructureMap262-sn.dll


Then its over to programming.

Message
We define a message with some properties that are sent from the client to the handler/server/service

public class PingMessage : NServiceBus.IMessage
{
public string Text;
}


Handler
Then a handler to consume these messages:

public class PingMessageHandler : NServiceBus.IHandleMessages<PingMessage>
{
public ILog Logger = LogManager.GetLogger(typeof(PingMessageHandler));

public void Handle(PingMessage message)
{
Logger.Debug(message.Text);
}
}


Unit testing
Normally I would have made Logger static readonly but we want to access this in our unit test

[TestFixture]
public class PingMessageHandlerFixture
{
[Test]
public void SendMessage()
{
Test.Initialize(typeof(PingMessage).Assembly);
var logger = A.Fake<log4net.ILog>();

Test.Handler<PingMessageHandler>()
.WithExternalDependencies(x => x.Logger = logger)
.OnMessage<PingMessage>(x => x.Text = "hello world");

A.CallTo(() => logger.Debug("hello world")).MustHaveHappened();
}
}


And the test goes green!

Great start :)

References:
www.nservicebus.com
fakeiteasy