-
Notifications
You must be signed in to change notification settings - Fork 26
Home
MicroBus is a simple in process mediator for .NET
PM> Install-Package Enexure.MicroBus.Autofac
I wanted a super simple mediator built in support for global handlers that's easy to use and configure.
To use MicroBus first you'll need to add the package Enexure.MicroBus.Autofac
to your project. The next step is to create a message you'll be handling. Messages usually fall under the categories of Commands, Events, and Queries (Request, Response).
First up we'll create a CreatePostCommand, this command will create a new post for a blog.
public class CreatePostCommand : ICommand
{
public Guid Id { get; }
public string Title { get; }
public CreatePostCommand(Guid id, string title)
{
Id = id;
Title = title;
}
}
Next we'll create a CommandHandler
to handle the command. A command handler will implement the ICommandHandler<>
interface.
public CreatePostCommandHandler : ICommandHandler<CreatePostCommand>
{
public async Task Handle(CreatePostCommand command)
{
// Saves a new post to the database
}
}
Now that we have both a message and a handler, it's time to register them with MicroBus. We'll start off by creating a new busBuilder.
var busBuilder = new BusBuilder()
When registering a handler there are two options we can take, you can register the command handler explicitly.
busBuilder.RegisterCommandHandler<CreatePostCommand, CreatePostCommandHandler>();
Or you can scan an assembly to find all the handlers.
busBuilder.RegisterHandlers(assembly);
Once your registrations are sorted out then it's just a matter of adding MicroBus to your DI container. Here is now we register MicroBus to Autofac. We'll start by creating a container builder, then register MicroBus and build the container.
var autofacContainer = new ContainerBuilder()
.RegisterMicroBus(busBuilder)
.Build();
Now that MicroBus and Autofac have been setup lets look at how they're used. For the next sample we'll look at a Web.Api project. I'll also assume the Autofac container has been already hooked up.
public class CreatePostController
{
readonly IMicroBus microBus;
public CreatePostController(IMicroBus microBus)
{
this.microBus = microBus;
}
public async Task Put(CreatePostModel model)
{
var createPostCommand = MapModelToCommand<CreatePostCommand>(model);
await microBus.SendAsync(createPostCommand);
}
}
And that's our first step into getting setup with MicroBus. And if you were wondering about how we can make that last class less verbose, because it really is mostly boiler-plate code, then you're on the right path! See if you can connect routes directly to MicroBus, via a Message Handler.