Created
April 9, 2024 18:03
-
-
Save VincentH-Net/a3a5c77904f250c2b391e294d595cd5d to your computer and use it in GitHub Desktop.
ASP.NET Core Minimal API's Endpoints registration helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Endpoints registration helper | |
// Enables DI for a group of endpoints to reduce init code and repeating parameters across endpoints | |
// Usage in e.g. Program.cs: | |
app.RegisterEndpoints( | |
typeof(CatalogEndpoints), | |
typeof(BasketsEndpoints) | |
); | |
// Implementation: | |
public interface IEndpoints | |
{ | |
void Register(IEndpointRouteBuilder routeBuilder); | |
} | |
public static class WebApplicationExtensions | |
{ | |
public static void RegisterEndpoints(this WebApplication app, params Type[] endpointsTypes) | |
{ | |
foreach (var endpointsType in endpointsTypes) | |
{ | |
((IEndpoints)ActivatorUtilities.CreateInstance(app.Services, endpointsType)) | |
.Register(app); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment