Home > Enterprise >  Resolving dependencies in a Func<T> that is moved to a separate class file
Resolving dependencies in a Func<T> that is moved to a separate class file

Time:09-09

I'm working with a codebase (Minimal APIs : .NET 6) which exposes a custom middleware (UseCustomMiddleware) that is added to IApplicationBuilder via extension methods.

The second parameter of UseCustomMiddleware is a Func<HttpRequest, Identity, Message, ... Task<(bool Pass, Error Error)> that act as a predicate for providing authentication mechanism.

Here's the layout in Program.cs:

builder.Services.AddScoped<AuthenticationService>();

var app = builder.Build();
    
app.UseCustomMiddleware<IContract,Methods>("/", async (httpRequest, accessibility, message, ...) =>
{
    //resolving dependencies here is not a problem.
    var authenticationService = app.Services.CreateScope().ServiceProvider.GetRequiredService<AuthenticationService>();
    //the rest of logic continues...
});

Everything works fine but the logic inside lambda is getting lengthier and lengthier and I need to move that to a separate class file.

I could create a static class and define the same static method with the signature of Func<...> and reference it in place of lambda but then I don't know how to resolve dependencies in there.

What is the proper way to achieve this?

CodePudding user response:

Not sure what UseCustomMiddleware is but you don't need app.Services.CreateScope().ServiceProvider... (also you don't dispose the scope which is bad). Middleware should have access to HttpContext, which has RequestServices property which you should use to resolve services. In theory you can try to get it from HttpRequest:

app.UseCustomMiddleware<IContract,Methods>("/", async (httpRequest, accessibility, message, ...) =>
{
    var authenticationService = httpRequest.HttpContext.RequestServices.GetRequiredService<AuthenticationService>();
});

Also see samples in the docs, especially for middlewares extracted into classes, I would argue they are more suitable for complex logic then ones with Func handlers.

  • Related