-
Notifications
You must be signed in to change notification settings - Fork 0
4. Adding an ASP.NET Core API Endpoint
The command pipeline is exposed as middleware, but the easiest way to include it in your application is to add specific endpoint routing using the extension methods within this library.
In order to use the middleware, you need to register the required services. This can be done in the ConfigureServices method of your Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// register the command pipeline dependencies
services.AddCommandBus(
new List<Assembly>
{
// assemblies that contain commands that should be registered
},
(opts) =>
{
// further configuration options
});
}To add the command pipeline to your api, simply use the MapCommandEndpoint() extension method in the Configure method of your Startup.cs file.
This will add the "/command" route to your api. If you want to specify the route, you can use the overload as demonstrated in the example below.
app.UseEndpoints(endpoints =>
{
// add the command endpoint
// ----------------------------- //
endpoints.MapCommandEndpoint();
// OR
endpoints.MapCommandEndpoint("custom/command-route");
// ----------------------------- //
endpoints.MapControllers();
});The CommandMiddleware class encapsulates a single generic command endpoint that only accepts POST requests.
If you don't want to use the extension methods described above, you can add this class as middleware and configure the pipeline as you see fit.
For reference, the MapCommandEndpoint extension branches the pipeline...
/// <summary>
/// Adds a command pipeline endpoint to the <see cref="IEndpointRouteBuilder"/>
/// with the specified template.
/// </summary>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add command endpoint to.</param>
/// <param name="pattern">The URL pattern of the command endpoint.</param>
/// <returns>A convention routes for the command endpoint.</returns>
public static IEndpointConventionBuilder MapCommandEndpoint(
this IEndpointRouteBuilder endpoints,
string pattern)
{
var pipeline = endpoints
.CreateApplicationBuilder()
.UseMiddleware<CommandMiddleware>()
.Build();
return endpoints
.MapPost(pattern, pipeline)
.WithDisplayName("Command Pipeline");
}