Now we will create a message handler within our service.
Add a new class to the service called
UserCreator.cs
.Add three namespaces to the using block of the class file:
using NServiceBus; using NServiceBus.Logging; using UserService.Messages.Commands;
Mark the class as
public
.Implement
IHandleMessages<CreateNewUserCmd>
.Implement the interface using Visual Studio's tools. This will generate a
Handle(CreateNewUserCmd message)
stub method.
Normally we would want to create the user here with calls to a database, but we don't have time for that! We're on a mission, so let's just demonstrate what would be happening by logging a message.
It is worth mentioning that a new feature in NServiceBus 4.0 is the ability to use any logging framework you like, without being dependent upon that framework. NServiceBus can automatically hook up to log4net or NLog—just add a reference to either assembly, and NServiceBus will find it and use it. You can even roll your own logging implementation if you wish.
However, it is not required to pick a logging framework at all. NServiceBus internalizes log4net, which it will use (via the NServiceBus.Logging
namespace) if you don't explicitly include a logging library. This is what we will be doing in our example.
Now let's finish our fake implementation for the handler:
When you're done, your class should look like this:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UserService.Messages.Commands; using NServiceBus; namespace UserService { public class UserCreator : IHandleMessages<CreateNewUserCmd> { private static readonly ILog log = LogManager.GetLogger(typeof(UserCreator)); public void Handle(CreateNewUserCmd message) { log.InfoFormat("Creating user '{0}' with email '{1}'", message.Name, message.EmailAddress); } } }
Now we have a command message and a service endpoint to handle it. It's OK if you don't understand quite how it all connects quite yet. Next we need to create a way to send the command.