EndpointExtensions.cs 915 B

123456789101112131415161718192021222324252627282930313233
  1. using System.Reflection;
  2. namespace Web.Api.Extensions;
  3. public static class EndpointExtensions
  4. {
  5. public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
  6. {
  7. var endpointTypes = assembly.DefinedTypes.Where(type => type is {
  8. IsAbstract: false,
  9. IsInterface: false
  10. } && type.IsAssignableTo(typeof(IEndpoint))).Select(type => ServiceDescriptor.Transient(typeof(IEndpoint), type)).ToArray();
  11. foreach (var descriptor in endpointTypes)
  12. {
  13. services.Add(descriptor);
  14. }
  15. return services;
  16. }
  17. public static IApplicationBuilder MapEndpoints(this WebApplication app)
  18. {
  19. var endpoints = app.Services.GetRequiredService<IEnumerable<IEndpoint>>();
  20. foreach (var endpoint in endpoints)
  21. {
  22. endpoint.MapEndpoint(app);
  23. }
  24. return app;
  25. }
  26. }