Skip to content

5. Using the Command Framework Only

Alex McNair edited this page Apr 19, 2021 · 1 revision

This library provides the necessary bindings to quickly and easily add command processing pipeline as an endpoint in an ASP Core API.

However, if you want to configure the endpoint yourself, or want to use the pipeline in a different context, you can.

You can still use the command pipeline and associated types.

Dependencies

To use the framework you will need to register the dependencies.

var services = new ServiceCollection();

services.AddCommandBus(
    new List<Assembly>
    {
        // assemblies that contain commands that should be registered
    },
    (opts) =>
    {
        // further configuration options
    });

var serviceProvider = services.BuildServiceProvider();

CommandBus

To execute the pipeline you need the registered ICommandBus instance. Then call the SendAsync(...) method, passing in...

  • The command instance
  • The command name
  • A command metadata instance
  • Optionally, a boolean value indicating whether the command should be validated, or validated and executed.
// given the following command

[CommandName("Api/AddUser")]
public class AddUser : ICommand
{
    public AddUser(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }

    public int Id { get; }

    public string Name { get; }
}

// -------------------------------------------------------------------------- //

var commandBus = serviceProvider.GetRequiredService<ICommandBus>();

var commandName = "Api/AddUser";

var command = new AddUser(1, "Jake");

var correlationId = Guid.NewGuid().ToString();

var validateOnly = false;

var metadata = new CommandMetadata(commandName, DateTime.UtcNow, correlationId);

await commandBus.SendAsync(command, commandName, metadata, validateOnly);

Clone this wiki locally