0

I have this:

app
    .Use(async (context, next) =>
    {
        await next();
        StatusCode(DB.AddRequest(context, context.Response.StatusCode < 400));
    });

Basically, this code is just adding some HTTP context information to a (MariaDB) database. This is not simple logging but it also triggers a warning system when there are too many invalid requests. It works fine if I make AddRequest a local function that retrieves the DB context from the services and then calls this method in the DB context.
However, when I use e.g. app.MapGet() then I can just use:

app.MapGet("/action/{name}", (HttpContext context, RequestContext db, string name) => ...

And DI will include the DB context in the call.
Is it possible to do the same with app.Use() and let DI insert the DB context in this call, as calling the service scope to retrieve the DB and then call it just doesn't look pretty.
Just curious if that would work in a minimal Api.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Wim ten Brink
  • 25,901
  • 20
  • 83
  • 149

1 Answers1

3

Use RequestServices property of the context:

app
    .Use(async (context, next) =>
    {
        await next();
        var db = context.RequestServices.GetRequiredService<RequestContext>();
    });
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Yeah, that works, but is the thing I want to avoid. This is using the service scope I've mentioned. – Wim ten Brink Jan 01 '23 at 01:18
  • 1
    @WimtenBrink no, it seems to be the only way. Minimal API endpoint handlers which support "open" (type and/or number of) parameters accept `Delegate` as parameter, there is no such overloads for middlewares via `Use`. – Guru Stron Jan 01 '23 at 17:32