3.1Kпросмотров
48.1%от подписчиков
15 января 2026 г.
📷 ФотоScore: 3.5K
⚡️ Автоматическая регистрация Minimal APIs в .NET - без ручного маппинга Если в проекте 20+ endpoint’ов, app.MapGet/MapPost превращается в ад.
Решение - авторегистрировать endpoints через DI. Идея:
1) Делаешь общий интерфейс IEndpoint
2) Каждый endpoint реализует его
3) На старте приложения сканируешь сборку, регистрируешь все реализации в DI
4) Достаёшь их из DI и вызываешь MapEndpoints() Плюсы:
✅ чистый Program.cs ✅ каждый endpoint в отдельном файле ✅ масштабируется без хаоса ✅ легко тестировать и поддерживать Пример паттерна: builder.Services.AddEndpoints(typeof(Program).Assembly); public interface IEndpoint
{ void Map(IEndpointRouteBuilder app);
} public static class EndpointExtensions
{ public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly) { var endpoints = assembly.DefinedTypes .Where(t => !t.IsAbstract && !t.IsInterface && typeof(IEndpoint).IsAssignableFrom(t)) .Select(t => ServiceDescriptor.Transient(typeof(IEndpoint), t)) .ToArray(); services.TryAddEnumerable(endpoints); return services; } public static void MapEndpoints(this WebApplication app) { foreach (var endpoint in app.Services.GetServices<IEndpoint>()) endpoint.Map(app); }
}