Created
April 20, 2024 06:41
-
-
Save anacondaf/2f4e61403f4b06107a2985034a2fcca3 to your computer and use it in GitHub Desktop.
Example of collecting API endpoints. Considering how to get type from assembly in line assembly.GetTypes()...
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
public static class EndpointExtensions | |
{ | |
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly) | |
{ | |
var types = assembly | |
.GetTypes() | |
.Where( | |
t => | |
t is { IsInterface: false, IsAbstract: false } && | |
typeof(IEndpoint).IsAssignableFrom(t) | |
) | |
.Select(t => new ServiceDescriptor(typeof(IEndpoint), t, ServiceLifetime.Transient)) | |
.ToList(); | |
services.TryAdd(types); | |
return services; | |
} | |
public static IApplicationBuilder MapEndpoints(this IApplicationBuilder app, IEndpointRouteBuilder routeBuilder) | |
{ | |
var endpoints = app.ApplicationServices.GetRequiredService<IEnumerable<IEndpoint>>(); | |
foreach (var endpoint in endpoints) | |
{ | |
var endpointTypeName = endpoint.GetType().Name; | |
var routePrefix = endpointTypeName[..^"Endpoint".Length]; | |
endpoint.MapEndpoint(routeBuilder, routePrefix); | |
} | |
return app; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment