40 lines
1.3 KiB
C#
40 lines
1.3 KiB
C#
using Emergence.api.Interfaces;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using System.Reflection;
|
|
|
|
namespace Emergence.api.Extensions;
|
|
|
|
public static class EndpointExtension
|
|
{
|
|
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
|
|
{
|
|
// Find all classes that implement IEndpoint and register them for DI
|
|
ServiceDescriptor[] serviceDescriptors = assembly
|
|
.DefinedTypes
|
|
.Where(type => type is { IsAbstract: false, IsInterface: false } &&
|
|
type.IsAssignableTo(typeof(IEndpoint)))
|
|
.Select(type => ServiceDescriptor.Transient(typeof(IEndpoint), type))
|
|
.ToArray();
|
|
|
|
services.TryAddEnumerable(serviceDescriptors);
|
|
|
|
return services;
|
|
}
|
|
|
|
public static IApplicationBuilder MapEndpoints(this WebApplication app, RouteGroupBuilder? routeGroupBuilder = null)
|
|
{
|
|
IEnumerable<IEndpoint> endpoints = app.Services
|
|
.GetRequiredService<IEnumerable<IEndpoint>>();
|
|
|
|
IEndpointRouteBuilder builder =
|
|
routeGroupBuilder is null ? app : routeGroupBuilder;
|
|
|
|
foreach (IEndpoint endpoint in endpoints)
|
|
{
|
|
endpoint.MapEndPoint(builder);
|
|
}
|
|
|
|
return app;
|
|
}
|
|
}
|