skip to content

In ASP.NET Core Minimal APIs, when would you use AddEndpointFilterFactory instead of AddEndpointFilter, and what runs once versus per request?

level: seniorimportance: should knowfreq 30%

answer

  1. build time versus request time
  2. EndpointFilterFactoryContext.MethodInfo
  3. inspect the handler's parameters once
  4. return next unchanged to opt out
  5. ApplicationServices is the root provider

basics

~20 s

Use a filter factory when a group-wide filter must adapt to each handler: the factory runs once per endpoint at build time with the handler's MethodInfo, and returns either a per-request EndpointFilterDelegate or next unchanged to skip that endpoint.

solid answer

~40 s

`AddEndpointFilterFactory` takes a `Func<EndpointFilterFactoryContext, EndpointFilterDelegate, EndpointFilterDelegate>`. The outer function runs **once per endpoint** when the endpoint is built; it receives the handler's `MethodInfo` and `ApplicationServices` (the root provider) plus the `next` delegate. The delegate it returns runs **per request**. That split lets a filter on a group inspect each handler's signature once, find the index of a `truckId` parameter, cache reflection results, and return `next` unchanged for handlers it does not apply to, which adds nothing to those requests; if every factory on an endpoint does that, the filter pipeline is skipped. Per-request services still come from `HttpContext.RequestServices`. Every `AddEndpointFilter` overload is itself built on `AddEndpointFilterFactory`, so factories and plain filters share one ordered list.

code

csharp · 20 lines
csharp
fleet.AddEndpointFilterFactory((factoryContext, next) =>
{
    var index = Array.FindIndex(factoryContext.MethodInfo.GetParameters(),
        p => p.ParameterType == typeof(int) && p.Name == "truckId");

    if (index < 0)
    {
        return next;
    }

    return async invocationContext =>
    {
        var truckId = invocationContext.GetArgument<int>(index);
        var store = invocationContext.HttpContext.RequestServices
            .GetRequiredService<IFleetStore>();
        return await store.TruckExistsAsync(truckId, invocationContext.HttpContext.RequestAborted)
            ? await next(invocationContext)
            : TypedResults.NotFound();
    };
});

go deeper

for a junior

Recall that a filter factory has an outer function that runs when the endpoint is built and an inner delegate that runs on each request.

for a middle

Explain what EndpointFilterFactoryContext carries, why returning next opts an endpoint out, and that the AddEndpointFilter overloads are built on the factory API.

for a senior

Use factories to make group-wide filters safe and cheap: signature-aware argument lookup, reflection hoisted to build time, scoped services only from RequestServices, no layer for endpoints that do not need it.

for a principal

Judge when a convention-driven factory is clearer than explicit per-endpoint filters: it removes repetition but hides behaviour behind parameter names, so naming rules become part of the API contract.

## Two moments in a filter's life An endpoint filter has a **build-time** part and a **request-time** part. `AddEndpointFilterFactory` exposes both: ```csharp builder.AddEndpointFilterFactory((factoryContext, next) => { // build time: once per endpoint return async invocationContext => { // request time: every request return await next(invocationContext); }; }); ``` - The outer lambda receives an **`EndpointFilterFactoryContext`** and the next `EndpointFilterDelegate`. It runs once for each endpoint the factory is attached to, when that endpoint is built. - It returns the **`EndpointFilterDelegate`** that runs on each request. - `EndpointFilterFactoryContext.MethodInfo` is the handler's method (for a lambda, the compiler-generated method, with real parameter names and types). `ApplicationServices` is the application's root service provider. `AddEndpointFilter<T>()`, `AddEndpointFilter(instance)` and `AddEndpointFilter(lambda)` are all implemented by calling `AddEndpointFilterFactory` with a factory that wraps the filter, so they share the same `FilterFactories` list and the same ordering rules. ## When a factory is the right tool - **A group filter that depends on each handler's signature.** On `/api/v1/fleet`, only some handlers take a `truckId`. A factory finds the parameter's index once per endpoint instead of hard-coding `GetArgument<int>(0)`. - **Opting out per endpoint.** Returning `next` unchanged means the factory adds no layer for that endpoint. If every factory on an endpoint returns `next` unchanged, the framework detects that nothing was wrapped and skips the filter pipeline entirely. - **Expensive, reusable setup.** Reflection over attributes on `MethodInfo`, a compiled accessor or a singleton fetched from `ApplicationServices` is computed once and captured by the per-request closure. ## The fleet example ```csharp fleet.AddEndpointFilterFactory((factoryContext, next) => { var parameters = factoryContext.MethodInfo.GetParameters(); var index = Array.FindIndex(parameters, p => p.ParameterType == typeof(int) && p.Name == "truckId"); if (index < 0) { return next; // no truckId: no filter for this endpoint } return async invocationContext => { var truckId = invocationContext.GetArgument<int>(index); var store = invocationContext.HttpContext.RequestServices .GetRequiredService<IFleetStore>(); return await store.TruckExistsAsync(truckId, invocationContext.HttpContext.RequestAborted) ? await next(invocationContext) : TypedResults.NotFound(); }; }); ``` `GET /api/v1/fleet/trucks` (no `truckId`) gets no filter at all; every truck-specific endpoint gets the guard at the right argument index, whatever position `truckId` holds in its handler. ## Which service provider, when | Need | Use | Why | |---|---|---| | a singleton for every request | `factoryContext.ApplicationServices` at build time | resolved once and captured | | a scoped service such as a store or `DbContext` | `invocationContext.HttpContext.RequestServices` at request time | the same instance the handler gets in that request | | a scoped service at build time | nothing; this is a bug | the root provider has no request scope | Resolving a scoped service from `ApplicationServices` either throws (scope validation is on in Development) or quietly creates a long-lived instance shared by every request. ## Common mistakes 1. Doing per-request work in the outer lambda, which runs only once per endpoint. 2. Doing reflection in the inner lambda, paying for it on every request. 3. Returning a pass-through lambda (`ctx => next(ctx)`) instead of `next` itself, which keeps a useless layer and prevents the pipeline from being skipped. 4. Assuming the factory runs once per group. It runs once per endpoint in the group, nested groups included. ## What interviewers listen for - The split: build-time factory per endpoint, per-request delegate per call. - What `EndpointFilterFactoryContext` carries (`MethodInfo`, `ApplicationServices`) and what it does not (any request). - Returning `next` to opt out, and the zero-cost path when no factory wraps anything. - Scoped services from `RequestServices`, never from the root provider.

  • What does EndpointFilterFactoryContext.MethodInfo hold for a lambda handler?
    The `MethodInfo` of the compiler-generated method behind the lambda. Its parameters keep the names and types you wrote, such as `int truckId`, so `GetParameters()` works for signature checks. Its declaring type and method name are compiler-generated, so match on parameters or attributes, not on the method's name.
  • Why return next itself rather than ctx => next(ctx) when the filter does not apply?
    Returning the same delegate tells the framework the factory added nothing. When every factory on an endpoint returns the delegate it was given, the request delegate is built without a filter pipeline, so the endpoint pays no per-request cost. A pass-through lambda is a real layer and defeats that check.

  • The outer lambda of AddEndpointFilterFactory runs on every request.
  • A filter factory runs once per group, shared by all its endpoints.
  • Resolve scoped services from EndpointFilterFactoryContext.ApplicationServices inside the factory.
  • Returning next unchanged short-circuits the endpoint with an EmptyHttpResult.
  • Factory filters live in a separate list that runs before plain endpoint filters.