Saturday, October 3, 2026

C# Dependency Injection: What Happens When the Same Service Is Registered Twice?

In a .NET 10 web service, I recently found ILogger registered twice in Program.cs: 

services.AddSingleton<ILogger>(sp =>
    new ControlPlaneLogger(
        sp.GetRequiredService<IArchitecturalPlanesFactory>()
          .GetControlPlaneLogger()));
services.AddSingleton<ILogger>(sp =>
    new ControlPlaneLogger(
        sp.GetRequiredService<IArchitecturalPlanesFactory>()
          .GetDataPlaneLogger()));

No class in the project injected ILogger, so I wanted to know what happens when the same interface is registered more than once. The duplicate registrations in Program.cs did not throw an exception.

I unearthed the following from Microsoft's documentation (Service registration):

In plain English, the last registered ILogger is the one injected into a class constructor. In the original duplicate-registration example, the bolded registration is the one DI will resolve for ILogger:

services.AddSingleton<ILogger>(sp =>
    new ControlPlaneLogger(
        sp.GetRequiredService<IArchitecturalPlanesFactory>()
          .GetControlPlaneLogger()));
services.AddSingleton<ILogger>(sp =>
    new ControlPlaneLogger(
        sp.GetRequiredService<IArchitecturalPlanesFactory>()
          .GetDataPlaneLogger()));




No comments :

Post a Comment