Skip to main content


Showing posts from December, 2023

DI-Y: Crafting Code with Multiple Services Using IEnumerable in Dependency Injection

Registering Services for IEnumerable Injection Service Registration Fundamentals Service registration is the process of telling the DI container how to create instances of a service, typically done at application startup. Registering Services for IEnumerable When services implement a common interface, you can register them in such a way that the DI container can provide an IEnumerable of these services. In .NET, for example: services.AddTransient<ICommonService, ServiceA>(); services.AddTransient<ICommonService, ServiceB>(); Why would you register mulitple instances of the same interface? One use-case is that it is the same service with a different configuration. Here is an example of how that would look: services.Configure<CustomOption>("Opt1", configuration.GetSection("Options1")); services.Configure<CustomOption>("Opt2", configuration.GetSection("Options2")); builder.Services.AddSingleton<ICommonService,Servic