C
C#2mo ago
Brady Kelly

✅ Minimal API: Pass app config to IEndpointRouteBuilder

I am using route builders to map routes for a minimal API, like this:
public static class LicenseApplicationEndpoints
{
private static EndpointsConfig _config = new EndpointsConfig();

public static void RegisterLicenseApplicationEndPoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup($"{_config.RoutePrefix}/licenseApplications");

group.MapGet("/forUser{userId:guid}",
([FromServices] ILicenseApplicationService service, Guid userId) =>
service.GetLicenseApplicationsForUser(userId));
}
}
public static class LicenseApplicationEndpoints
{
private static EndpointsConfig _config = new EndpointsConfig();

public static void RegisterLicenseApplicationEndPoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup($"{_config.RoutePrefix}/licenseApplications");

group.MapGet("/forUser{userId:guid}",
([FromServices] ILicenseApplicationService service, Guid userId) =>
service.GetLicenseApplicationsForUser(userId));
}
}
I'd like to access the app's IConfiguration from within these classes and am hoping there is a better way than reading config values in Program and passing them to each register endpoints method. I'd really like to receive config values or IConfiguration as ctor parameters.
2 Replies
Becquerel
Becquerel2mo ago
Would making your extension method off of WebApplication instead be viable?
public static void AddAppEndpoints(this WebApplication app)
{
// app.Services.GetRequiredService()...
// app.Configuration.GetValue<>()...
app.MapGet("/current", (PostStore store) => store.Current.ToJsonOrNotFound());
public static void AddAppEndpoints(this WebApplication app)
{
// app.Services.GetRequiredService()...
// app.Configuration.GetValue<>()...
app.MapGet("/current", (PostStore store) => store.Current.ToJsonOrNotFound());
This snippet is from my toy web app
Brady Kelly
Brady Kelly2mo ago
Thanks, it looks like it would be, as WebApplication also seems to implement IEndpointRouteBuilder, allowing me to call app.MapGroup. I'll have to have a look in a short while.