ServiceComposer.AspNetCore

Composition requests filters

Available starting with v2.3.0

Composition requests filters allow intercepting composition requests to specific composition handlers. Contrary to endpoint filters that are generic HTTP filters, composition filters sit right in front of the composition handlers they are configured to intercept.

Defining composition requests filters

Composition requests filter can be defined as attributes or as classes.

Defining composition requests filters as attributes

Create an attribute that inherits from CompositionRequestFilterAttribute like in the following snippet:

public class SampleCompositionFilterAttribute : CompositionRequestFilterAttribute
{
    public override ValueTask<object> InvokeAsync(CompositionRequestFilterContext context, CompositionRequestFilterDelegate next)
    {
        return next(context);
    }
}

snippet source | anchor

[!NOTE] The InvokeAsync implementation is responsible to invoke the next filter in the pipeline.

Apply the attribute to the composition handlers to intercept:

public class SampleHandler : ICompositionRequestsHandler
{
    [SampleCompositionFilter]
    [HttpGet("/sample/{id}")]
    public Task Handle(HttpRequest request)
    {
        return Task.CompletedTask;
    }
}

snippet source | anchor

Defining composition requests filters as classes

Create a class that implements the ICompositionRequestFilter<T> interface, where the generic T parameter is the composition handler type to intercept:

public class SampleCompositionFilter : ICompositionRequestFilter<SampleHandler>
{
    public ValueTask<object> InvokeAsync(CompositionRequestFilterContext context, CompositionRequestFilterDelegate next)
    {
        return next(context);
    }
}

snippet source | anchor

The above snippet defines a filter intercepting requests to the SampleHandler composition handler.

[!NOTE] Filters defined as classes implementing the ICompositionRequestFilter<T> interface will be automatically registered in DI as transient, and can use DI to resolve dependencies.

When to use composition filters vs endpoint filters

ServiceComposer provides two filter extension points. Choosing the right one depends on the scope of interception needed.

Use endpoint filters when:

Use composition filters when:

In short: endpoint filters are coarse-grained (the whole endpoint), composition filters are fine-grained (a specific handler).