Skip to content

[API Proposal]: Dependency Injection - Add explicit way of binding multiple interfaces to the same singleton instance #70004

Closed

Description

@FooRider

Background and motivation

When using Microsoft.Extensions.DependencyInjection, there is no way to explicitly bind multiple interfaces to a singleton instance of their implementation. Common workaround is to create ServiceDescriptor with implementationFactory that calls IServiceProvider.GetRequiredService() method.

This approach has two issues with current implementation:

  • implementationFactory function hides dependency and therefore ServiceProvider can not find missing bindings during validation.
  • The fact that the same instance is injected under different ServiceDescriptors is lost, potentially causing the ServiceProvider to dispose the same object multiple times.

Minimum example of the disposing issue:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using (var host = Host.CreateDefaultBuilder(args)
  .UseDefaultServiceProvider(options =>
  { options.ValidateOnBuild = true; })
  .ConfigureServices(services =>
  {
    services.AddSingleton<NameAndGreetingGenerator>();
    services.AddSingleton<INameGenerator>(x => x.GetRequiredService<NameAndGreetingGenerator>());
    services.AddSingleton<IGreetingGenerator>(x => x.GetRequiredService<NameAndGreetingGenerator>());

    services.AddTransient<ExampleRunner>();
  })
  .Build())
{

  var gwn1 = host.Services.GetRequiredService<ExampleRunner>()
                          .GenerateGreetingWithName();
  Console.WriteLine(gwn1);

  var gwn2 = host.Services.GetRequiredService<ExampleRunner>()
                          .GenerateGreetingWithName();
  Console.WriteLine(gwn2);

}

class ExampleRunner
{
  private readonly INameGenerator nameGenerator;
  private readonly IGreetingGenerator greetingGenerator;

  public ExampleRunner(INameGenerator nameGenerator, IGreetingGenerator greetingGenerator)
  {
    Console.WriteLine($"Creating {nameof(ExampleRunner)}");
    this.nameGenerator = nameGenerator;
    this.greetingGenerator = greetingGenerator;
  }

  public string GenerateGreetingWithName()
    => greetingGenerator.GenerateGreeting(nameGenerator.GenerateName());
}

interface INameGenerator { string GenerateName(); }
interface IGreetingGenerator { string GenerateGreeting(string name); }

class NameAndGreetingGenerator : INameGenerator, IGreetingGenerator, IDisposable
{
  private readonly Random random = new Random();

  public NameAndGreetingGenerator() =>
    Console.WriteLine($"Creating {nameof(NameAndGreetingGenerator)}");

  public string GenerateName()
  {
    var chars = new List<char>();

    chars.Add((char)('A' + random.Next('Z' - 'A')));
    var length = random.Next(4, 10);
    while (chars.Count < length)
      chars.Add((char)('a' + random.Next('Z' - 'A')));

    return new string(chars.ToArray());
  }

  public string GenerateGreeting(string name) =>
    $"Welcome {name}!";

  public void Dispose() =>
    Console.WriteLine($"Disposing {nameof(NameAndGreetingGenerator)}");
}

Outputs:

Creating NameAndGreetingGenerator
Creating ExampleRunner
Welcome Xjcicxw!
Creating ExampleRunner
Welcome Jeudgnlkv!
Disposing NameAndGreetingGenerator
Disposing NameAndGreetingGenerator
Disposing NameAndGreetingGenerator

Minimum example of the validation issue (assume the same support classes and interfaces):

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using (var host = Host.CreateDefaultBuilder(args)
  .UseDefaultServiceProvider(options =>
  { options.ValidateOnBuild = true; })
  .ConfigureServices(services =>
  {
    //services.AddSingleton<NameAndGreetingGenerator>();
    services.AddSingleton<INameGenerator>(x => x.GetRequiredService<NameAndGreetingGenerator>());
    services.AddSingleton<IGreetingGenerator>(x => x.GetRequiredService<NameAndGreetingGenerator>());

    services.AddTransient<ExampleRunner>();
  })
  .Build())
{

  var gwn1 = host.Services.GetRequiredService<ExampleRunner>() // throws exception after host is built, when ExampleRunner is requested
                          .GenerateGreetingWithName();
  Console.WriteLine(gwn1);

  var gwn2 = host.Services.GetRequiredService<ExampleRunner>()
                          .GenerateGreetingWithName();
  Console.WriteLine(gwn2);

}

In this example, ServiceProvider validation doesn't reveal the fact that INameGenerator, nor IGreetingGenerator instances could be created using provided bindings, and doesn't throw an exception from .Build() method, allowing the program to continue and fail after initialization, when requesting ExampleRunner service.

API Proposal

Both of the current issues stem from the fact that ServiceDescriptor class currently doesn't know that multiple different service types are provided by the same instance of implementation type. There are multiple possible ways to encode this information into ServiceDescriptor class.

Possible solution # 1 - modify ServiceDescriptor class to contain multiple types as its ServiceType, in new property ServiceTypes.

public class ServiceDescriptor
{
  // ...
  public Type ServiceType { get; }
  
  public Type[] ServiceTypes { get; } // Add new property possibly containing multiple service types
  // ...
  // Also, add constructors accepting multiple serviceTypes
  public ServiceDescriptor(
    IEnumerable<Type> serviceTypes,
    Type implementationType,
    ServiceLifetime lifetime)
    : this(serviceTypes, lifetime
  {
    // ...
    ImplementationType = implementationType;
  }
  private ServiceDescriptor(
    IEnumerable<Type> serviceTypes,
    ServiceLifetime lifetime)
  {
    Lifetime = lifetime;
    ServiceTypes = serviceTypes.ToArray();
  }
}

API Usage

Usage of possible solution # 1:

hostBuilder.ConfigureServices(services => 
{
  var descriptor = new ServiceDescriptor(
    new[] { typeof(INameGenerator), typeof(IGreetingGenerator) },
    typeof(NameAndGreetingGenerator),
    ServiceLifetime.Singleton);
  services.Add(descriptor);
}

Using extension methods:

hostBuilder.ConfigureServices(services =>
{
  services.Add(new[] { typeof(INameGenerator), typeof(IGreetingGenerator) }, typeof(NameAndGreetingGenerator), ServiceLifetime.Singleton);
}

Another extension method using generics:

The name of this method should be different from "AddSingleton", because it could be confusing. Name of the extension method in the example is just a first proposal, a better name could be surely found.

hostBuilder.ConfigureServices(services =>
{
  services.AddMultiServiceSingleton<INameGenerator, IGreetingGenerator, NameAndGreetingGenerator>();
}

Alternative Designs

Another solution would require IoC container to check whether implementation type is already bound and use that binding to satisfy request for requested service type.

This could be problematic, since it would change current behavior.

Risks

Proposed solution will have consequences for current implementation of IoC containers. Each implementation would need to be able to work with ServiceDescriptors that have (ServiceType != null && ServiceTypes == null) and (ServiceType == null && ServiceTypes != null) and somehow implement the new scenario.

Proposed alternative solution will mean no changes in API interface, but would specify different behavior for container implementation. The risk for existing projects could be mitigated by new option in ServiceProviderOptions class that would enable this new behavior on request. Problem with this could be perhaps non-intuitive behavior when bindings do not have the same ServiceLifetime set.

Activity

  1. added
    api-suggestion
    on May 31, 2022
  2. ghost added
    untriaged
    on May 31, 2022
  3. added this to the Future milestone on May 31, 2022
  4. ghost removed
    untriaged
    on May 31, 2022
  5. Carsillas commented on Aug 18, 2023

    @Carsillas

    I agree with this proposal but I just want to mention the multiple IDisposable calls should be a nonissue as I think it seems to be the standard pattern that multiple calls to Dispose should do nothing.

    https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose (3rd paragraph)

  6. XavierCL commented on May 1, 2024

    @XavierCL

    I agree with this proposal but I just want to mention the multiple IDisposable calls should be a nonissue as I think it seems to be the standard pattern that multiple calls to Dispose should do nothing.

    Note that the dispose order is also affected, not only the number of calls.

    E.g.

    class ExampleNameRunner
    {
      private readonly INameGenerator nameGenerator;
    
      public ExampleNameRunner(INameGenerator nameGenerator)
      {
        this.nameGenerator = nameGenerator;
      }
    
      public string GenerateName()
        => nameGenerator.GenerateName();
    }
    
    class ExampleGreetingRunner
    {
      private readonly IGreetingGenerator greetingGenerator;
    
      public ExampleGreetingRunner(IGreetingGenerator greetingGenerator)
      {
        this.greetingGenerator = greetingGenerator;
      }
    
      public string GenerateGreeting()
        => greetingGenerator.GenerateGreeting();
    }

    If you instanciate ExampleNameRunner then ExampleGreetingRunner, the creation order will be the following:

    1. INameGenerator (Singleton)
    2. ExampleNameRunner
    3. IGreetingGenerator (Singleton)
    4. ExampleGreetingRunner

    Since the services are disposed in the reverse order (as they should), IGreetingGenerator will be disposed before ExampleNameRunner, which means ExampleNameRunner will hold a reference to a disposed singleton without itself having been disposed.

  7. wvpm commented on Jul 25, 2024

    @wvpm

    This is a very relatable issue. I sometimes run into it with configuration classes (1 config implementation implementing several config interfaces).

    I think the array of service types is not the right way to go. I'd rather have some helper method create multiple servicedescriptors as you now manually do.

    As for validation, I recommend adding a unit test just for DI that verifies you can resolve the services you want to expose.

  8. julealgon commented on Jul 25, 2024

    @julealgon

    Proposal makes sense to me and I've needed this many times in the past. However, I see zero reason why this is being limited to singletons.

    The new API should be implemented to work with all lifetimes.

    @wvpm

    I think the array of service types is not the right way to go. I'd rather have some helper method create multiple servicedescriptors as you now manually do.

    Why would you rather have N service descriptors registered? IMHO, the most "native" approach to this would be to have one descriptor and expand the current ServiceDescriptor.Type property into a Types array.

  9. wvpm commented on Jul 25, 2024

    @wvpm

    Why would you rather have N service descriptors registered? IMHO, the most "native" approach to this would be to have one descriptor and expand the current ServiceDescriptor.Type property into a Types array.

    The Microsoft DI package is meant to be compatible with all implementations. Expanding the ServiceDescriptor requires all implementations to also expand. Creating multiple ServiceDescriptors is something that already works. It just looks and feels weird. I previously ran into a similar issue, see #41050 (comment) .

  10. rosebyte commented on Feb 12, 2026

    @rosebyte
    Member

    Triage: sounds useful, we consider implementing it in future.

  11. danzuep commented on Feb 28, 2026

    @danzuep

    Triage: sounds useful, we consider implementing it in future.

    Good to hear! I'd proposed a simple way of implementing this in the ticket that's just been closed as a duplicate, with examples in a GitHub repository. The usage is as follows:

    services.AddSingleton<I1, I2, Concrete1>();
    services.AddTransient<I1, I2, I3, Concrete2>();
    services.AddScoped<I4, I5, I6, Service>();

    Alternative options I've also demonstrated in the sample project unit tests:

    services.AddAllOfType<Interface>(ServiceLifetime.Singleton);
    services.AddWithInterfaces<MemoryStream>(ServiceLifetime.Singleton);
    services.Add<Concrete>(ServiceLifetime.Singleton, typeof(I1), typeof(I2), typeof(I3));
    services.Add<Service>(ServiceLifetime.Scoped, provider => new Service(provider.GetRequiredService<I2>()), typeof(I4), typeof(I5));
    services.Add<Api>(ServiceLifetime.Transient, provider => new Api(provider.GetRequiredService<I5>()), typeof(I6), typeof(I7));

    I'd be very happy to prepare a PR for the dotnet runtime once we get agreement on what is useful and what isn't!

  12. AnorZaken commented on May 14, 2026

    @AnorZaken

    I agree with this proposal but I just want to mention the multiple IDisposable calls should be a nonissue as I think it seems to be the standard pattern that multiple calls to Dispose should do nothing.

    Note that the dispose order is also affected, not only the number of calls.

    E.g.

    class ExampleNameRunner
    {
    private readonly INameGenerator nameGenerator;

    public ExampleNameRunner(INameGenerator nameGenerator)
    {
    this.nameGenerator = nameGenerator;
    }

    public string GenerateName()
    => nameGenerator.GenerateName();
    }

    class ExampleGreetingRunner
    {
    private readonly IGreetingGenerator greetingGenerator;

    public ExampleGreetingRunner(IGreetingGenerator greetingGenerator)
    {
    this.greetingGenerator = greetingGenerator;
    }

    public string GenerateGreeting()
    => greetingGenerator.GenerateGreeting();
    }
    If you instanciate ExampleNameRunner then ExampleGreetingRunner, the creation order will be the following:

    1. INameGenerator (Singleton)
    2. ExampleNameRunner
    3. IGreetingGenerator (Singleton)
    4. ExampleGreetingRunner

    Since the services are disposed in the reverse order (as they should), IGreetingGenerator will be disposed before ExampleNameRunner, which means ExampleNameRunner will hold a reference to a disposed singleton without itself having been disposed.

    This is indeed an important issue that this proposal does not solve (since it's a separate tangential issue).
    It remains problematic that when a disposable class implements multiple interfaces, the lifetime of those interfaces could be subtly different, but the current Dispose pattern is unable to handle that, because typically callers just cast to IDisposable and then call Dispose, meaning the context of what the caller thinks it is disposing is unknown to the implementation of the Dispose method.

    The C# solution to a semi-similar problem, is when two interfaces have the same method signature, and then you solve it by explicit interface implementation --> this lets the implementation class differentiate what the caller thinks they are calling, and act accordingly. But since the pattern for IDisposable is to let the caller cast to the general IDisposable interface first, there is zero differentiation information available when the call reaches the implementing class.

    In conclusion the dispose pattern is subtly broken under multi-interface inheritance in C#, and in hindsight the only way to correctly implement dispose semantics would have been to use Duck-Typing just as foreach does: Add a dispose(...) keyword similar to foreach(...) have it resolve Dispose via Duck-Typing just like foreach: If an interface has a Dispose method, it compiles. Now the implementing class can implement differentiated Dispose methods via explicit interface implementation, which solves the broken dispose pattern.

    EDIT:
    Added a separate proposal for this:
    #128182

  13. self-assigned this
    on May 28, 2026
  14. rosebyte commented on May 29, 2026

    @rosebyte
    Member

    As far as I see, there are three concerns related to using registration factory to bind two interfaces to one instance like this:

    services.AddSingleton<INameGenerator>(sp => sp.GetRequiredService<IGenerator>());

    The first is that a registration factory hurts ValidateOnBuild by hiding dependencies. While this is true in general, here it is not an issue because we do not actually create a new instance. Whatever was validated when constructing INameGenerator is effectively reused for IGenerator as well.

    The second is that if the service is disposable, it is captured and disposed twice, which is the current behaviour of MEDI (MS Extensions DI). I am not sure we can call it a bug, as disposal should be idempotent, but it is definitely a footgun that needs to be addressed as such.

    The third is that the disposal order can be incorrect if an implementation is first resolved as a dependency A of another implementation and then again as another service B. If the other service relies on the implementation during its own disposal, it might fail because the implementation has already been disposed as the B service. This is again MEDI behaviour and something we need to fix anyway.

    That said, a registration factory is a perfectly valid way to bind two services to one implementation. Am I missing anything?

    Another question is if we should implement the proposal as a convenience API. I don't think so. For MEDI it’s not a major issue, but IServiceCollection is consumed by every third‑party container (Autofac, DryIoc, Lamar, Simple Injector, Castle Windsor, etc.), so all of them would need to cover change as well or start getting bug reports from users. While this might be acceptable for critical or high value changes, e.g. security hardening, it’s not justified for adding convenience API, I assume.

  15. added
    in-pr
    on May 29, 2026
  16. locked and limited conversation to collaborators on Jul 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-suggestionarea-Extensions-DependencyInjectionin-pr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions