using System; using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; namespace Default { public class Program { public static void Main(string[] args) { Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(builder => { builder.ConfigureServices((ctx, svcs) => { svcs.AddDefault(); svcs.AddTransient<IHandler, FooHandler>(); }).Configure((ctx, app) => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { context.RequestServices.GetRequiredService<IService>().Execute(); await context.Response.WriteAsync("Done"); }); }); }); }) .Build() .Run(); } } public interface IHandler { void Handle(); } public class DefaultHandler : IHandler { public void Handle() { Console.WriteLine("DefaultHandler.Handle"); } } public interface IHandlerProvider { IEnumerable<IHandler> GetHandlers(); } public class DefaultHandlerProvider : IHandlerProvider { private readonly IEnumerable<IHandler> _handlers; public DefaultHandlerProvider(IEnumerable<IHandler> handlers) { _handlers = handlers; } public IEnumerable<IHandler> GetHandlers() { return _handlers; } } public interface IService { void Execute(); } public class DefaultService : IService { private readonly IHandlerProvider _handlerProvider; public DefaultService(IHandlerProvider handlerProvider) { _handlerProvider = handlerProvider; } public void Execute() { var handlers = _handlerProvider.GetHandlers(); foreach (var handler in handlers) { handler.Handle(); } } } public static class ServiceCollectionExtensions { public static IServiceCollection AddDefault(this IServiceCollection services) { services.TryAdd(ServiceDescriptor.Transient<IService, DefaultService>()); services.TryAdd(ServiceDescriptor.Transient<IHandlerProvider, DefaultHandlerProvider>()); services.TryAddEnumerable(ServiceDescriptor.Transient<IHandler, DefaultHandler>()); return services; } } public class FooHandler : IHandler { public void Handle() { Console.WriteLine("FooHandler.Handle"); } } }