Home > Software engineering >  Best way to access a DBContext from the middleware?
Best way to access a DBContext from the middleware?

Time:01-02

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.

CodePudding user response:

Use RequestServices property of the context:

app
    .Use(async (context, next) =>
    {
        await next();
        var db = context.RequestServices.GetRequiredService<RequestContext>();
    });
  • Related