Repository navigation
Description
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
Carsillas commentedon Aug 18, 2023
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)
XavierCL commentedon May 1, 2024
Note that the dispose order is also affected, not only the number of calls.
E.g.
If you instanciate ExampleNameRunner then ExampleGreetingRunner, the creation order will be the following:
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.
wvpm commentedon Jul 25, 2024
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.
julealgon commentedon Jul 25, 2024
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
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.Typeproperty into aTypesarray.wvpm commentedon Jul 25, 2024
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) .
rosebyte commentedon Feb 12, 2026
Triage: sounds useful, we consider implementing it in future.
danzuep commentedon Feb 28, 2026
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:
Alternative options I've also demonstrated in the sample project unit tests:
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!
AnorZaken commentedon May 14, 2026
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
foreachdoes: Add adispose(...)keyword similar toforeach(...)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
rosebyte commentedon May 29, 2026
As far as I see, there are three concerns related to using registration factory to bind two interfaces to one instance like this:
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.