Skip to content

Instantly share code, notes, and snippets.

@anacondaf
Created April 20, 2024 06:41
Show Gist options
  • Save anacondaf/2f4e61403f4b06107a2985034a2fcca3 to your computer and use it in GitHub Desktop.
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()...
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