Repository navigation
Description
Background and Motivation
When using the Microsoft.Extensions.DependencyInjection's ServiceviceDescriptor to register a service, you can register an instance, factory or implementationtype. This is great and generally works fine. However, when registering an open generic type, you can only use an implementationtype. Any other variant will cause runtime errors.
Proposed API
I propose adding a property to the ServiceDescriptor, along with a constructor to set the property like this:
namespace Microsoft.Extensions.DependencyInjection {
public class ServiceDescriptor
{
+ public Func<IServiceProvider, Type, object>? TypedImplementationFactory { get; }
+ /// <summary>
+ /// Initializes a new instance of <see cref="ServiceDescriptor"/> with the specified <paramref name="factory"/>.
+ /// </summary>
+ /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
+ /// <param name="factory">A factory used for creating service instances. The type parameter is the requested serviceType.</param>
+ /// <param name="lifetime">The <see cref="ServiceLifetime"/> of the service.</param>
+ public ServiceDescriptor(
+ Type serviceType,
+ Func<IServiceProvider, Type, object> factory,
+ ServiceLifetime lifetime)
+ : this(serviceType, lifetime)
+ {
+ if (serviceType == null)
+ {
+ throw new ArgumentNullException(nameof(serviceType));
+ }
+
+ if (factory == null)
+ {
+ throw new ArgumentNullException(nameof(factory));
+ }
+
+ TypedImplementationFactory = factory;
+ ImplementationFactory = provider => factory(provider, serviceType);
+ }Usage Examples
You would be able to use it when adding DI registrations as follows:
IServiceCollection serviceCollection = new ServiceCollection();
ServiceDescriptor descriptor = new (
typeof(IGenericService<>),
(IServiceProvider provider, Type requestedType) =>
provider.GetRequiredService<IGenericServiceFactory>()
.Build(requestedType),
ServiceLifetime.Singleton
);
serviceCollection.Add(descriptor);Where IGenericService<> and IGenericServiceFactory would be custom interfaces not part of the dotnet runtime code.
IGenericServiceFactory.Build(Type) would of course return an instance of that type.
Alternative Designs
I could not think of any other good solution.
A bad alternative solution required emitting dynamic wrapper classes.
Risks
I foresee two risks and two concerns regarding extra work due to obsolete code.
Risks:
- ServiceProviders would have to be edited to provide support for the TypedImplementationFactory. If a ServiceProvider does not support this, you would only find this out runtime possibly by a nullref, depending on implementation.
- The IServiceCollectionExtensions should be expanded with overloads for the TypedImplementationFactory, which might confuse programmers.
Extra work concerns, If the IServiceCollectionExtensions and ServiceDescriptor constructor using the ImplementationFactory were tagged as obsolete:
- Programmers using Microsoft.Extensions.DependencyInjection should update their code, resulting in extra work.
- The obsolete code should eventually be removed from Microsoft.Extensions.DependencyInjection, resulting in extra work.
Activity
[-]Dependency Injection[/-][+]Dependency Injection of Open Generics via factory[/+]wvpm commentedon Aug 19, 2020
I did work out an implementation in the CallSiteFactory which is used to actually resolve services.
I'll create a fork later to show the code changes.
eerhardt commentedon Aug 19, 2020
You don't need push rights to make a pull request. You can fork the repo yourself, and make a PR from your fork.
However, since this is proposing a new API you should wait until the API is reviewed and approved before creating a PR. See https://github.com/dotnet/runtime/blob/master/docs/project/api-review-process.md for more info.
carusology commentedon Aug 20, 2020
Unless the stance of Microsoft here, here or here changed, this isn't happening.
A good summary statement from @pakrym (Source):
While it's not a breaking change for consumers, they don't want a breaking change for other DI implementers who would need to support the new typed implementation factory API. You correctly identified this problem in your "Risks" section.
For reference, it's still fairly popular question on StackOverflow with no great answer.
wvpm commentedon Aug 20, 2020
Thanks @carusology for linking those. I couldn't find any related issues within this github and the stackoverflow post reveals the open wound. I could imagine that with .Net 5 Microsoft could consider real API changes. When they made .Net Core they changed a lot also. If they don't want to change the API for this feature specifically, perhaps they can bundle it with other features. It would be sad if the API is stuck in place due to implementers having to add features. That sounds very similar to ECMAScript '99-2015.
If I look at the before and after for implementers that do not support this feature, it would be runtime exception vs runtime exception. Where you just have to know that open generics can only be registered with an open generic implementation. Seems to me there is not that much to lose.
davidfowl commentedon Aug 23, 2020
.NET 5 is done, we can look at something for .NET 6 but we're not making any breaking changes in this space regardless. On top of that, any new requirement to the DI container abstraction needs to be implemented in all existing supported containers, that is the minimum bar for new features.
That said, I like this feature 😄
wvpm commentedon Aug 24, 2020
Good to hear .NET 5 is done.
I added a fallback option in the proposed API constructor. The TypedImplementationFactory variant now also sets the ImplementationFactory. This way, providers that don't support the TypedImplementationFactory can continue to use the ImplementationFactory. So if I use the TypedImplementationFactory constructor and my provider does not support it, it will work if the serviceType is not an open generic (as before). It will throw runtime exceptions with open generics (as before). So if a provider does not change anything, it will work the same as before. This allows providers to implement it at their pace.
If for some reason the ServiceDescriptor API may not be altered because not all implementors support it and the implementors depend on a TypedImplementationFactory, then you have a chicken-egg issue. So I hope dotnet takes the initiative and alters the API is a non-breaking way, so that the implementors can use the new API to update their code.
davidfowl commentedon Aug 24, 2020
That's not how changes to the DI system work. You need to take the initiative and see how the supported containers behave and how difficult this support would be to implement. When the rubber meets the road, we actually tests all known implementations as part of success criteria so it's not something we would commit then figure out.
We can mention the various authors to get some other opinions
dazinator commentedon Sep 24, 2020
I am creating a library to provide a "child container" feature for the native MS
ServiceProviderbut I have hit this problem with respect tosingleton open generic registrations. I just cannot solve it in a decent way, precisely due to this issue outlined. I've worked around it, by giving the user some options around how these registrations are dealt with when they are encountered, none of which are ideal. For example one option is to just throw when these descriptors are encountered - and there are usually atleast the following added by the Hosting layer:The issue (as already described) is that when a
singleton open genericdescriptor is registered, there is no ability to specify that you want the instance to be provided from "elsewhere". This is a problem for the parent --> child relationship I was aiming to achieve! In my case the child container needs to be able to resolve a singleton open generic from the parent container so it gets the same instance.This TypedImplementationFactory would only
partlysolve the problem - enabling me to do as @wvpm suggested:I say partly, because it doesn't address the last option that we have with closed type singleton registrations - the ability when the instance is provided to prevent the container from owning / tracking / disposing of that instance. When I ultimately provide a singleton instance that I have created "externally" (in my case via the parent container,) I want to hint to the container that this singleton instance is "external" like I can with closed type singleton registrations when providing an instance. Please - if you do decide to make the changes necessary to solve this issue, please can you also go the whole hog and add this option? @wpvm do you have any thoughts on what that api might look like - i.e to indicate its an "external" instance that shouldn't be tracked for disposal?
51 remaining items
davidfowl commentedon Jun 5, 2025
It’s not happening in .NET 10. You can look at the issue milestones to get clues as to what is being actively considered in a release of .NET
Alxandr commentedon Nov 24, 2025
Another really neat thing this would enable would be registering "self-factories".
Example:
I tried a similar pattern for metrics in services:
The workaround is to create an extra interface and wrapper class, so it's not too bad, but there's more things to name, which as we all know is one of the hardest things in programming :P.
rosebyte commentedon Feb 12, 2026
Triage: this is a feature gap compared to other frameworks, we should consider implementing in future.
Typeparameter overload to Microsoft.Extensions.DependencyInjection resolver delegate method #102970 as a duplicate of this issueCoreDX9 commentedon Feb 26, 2026
I have a derivative version that implements this feature. If interested, I can organize it into a PR.
CoreDX.Extensions.DependencyInjection
cincuranet commentedon Feb 26, 2026
@CoreDX9 Sure. But we need to first go through API review. Are you up for proposing something and work on refining it (if needed)?
CoreDX9 commentedon Mar 11, 2026
@cincuranet Yes, I'm sure.
Implementing this feature is not difficult. Just need
FactoryCallSiteto supportFunc<IServiceProvider, Type, object>. In my derivative version. To minimize changes to the original code, additional cache objects are used to bridge the two types of delegation. Public API is the same as the proposal.luizfbicalho commentedon May 2, 2026
I'm very interested in this feature, but I don't see any movement in this to add to the default DI
I don't see why the requested type wasn't in the parameter from the start.
Is there any option of DI Container that already has this feature?
CaptaiNiveau commentedon May 14, 2026
This would be very nice to forward the request from one ServiceProvider to another one. I'm currently building a small test project that supports loading and comparing contents of two different databases by running them side by side. I wanted to inject the relevant services from the secondary ServiceProvider (reference implementation/data) as keyed services, so I can simply request them like
IRepository<MyDatabaseObj> newRepository, [FromKeyedServices("ref")]IRepository<MyDatabaseObj> refRepository. It'd be nice if I could implement it like this:I could've used this feature for other purposes before as well, like injecting specific implementations based on some properties of the requested type (as was discussed already). So I'm definitely also interested in this feature!
rosebyte commentedon Jun 8, 2026
I spend some time looking at details. It's unfortunate the registered factory overloads weren't added with the implementation type overloads because on their own they're rather niche and won't worth all the overhead to make them supported by all containers. I understand the complains but the world of MEDI isn't perfect and this is one of the imperfect parts. I feel for everyone proposing the feature in this thread, I'd love to have it too but the same time I see that it would require a new factory shape that carries the requested Type, either as the proposed TypedImplementationFactory property or as a new descriptor subtype.
Implementing this in MSDI's own container would be straightforward. The problem is that MEDI.Abstractions is a contract every third-party container (Autofac, LightInject, DryIoc, SimpleInjector, Lamar, etc.) reads when adapting IServiceCollection. Each of them would need to recognise and honour the new descriptor shape themselves, and there's no way to provide a shim for them, as the target type is very specific information. A container that doesn't recognise the new shape would either fail at registration (and the application wouldn't be able to use it anymore) or silently fall back to the ImplementationFactory the proposal also fills in, which for an open generic always passes typeof(IFoo<>) rather than the true target type (as we don't have any way to express the requested type in a backward compatible way).
luizfbicalho commentedon Jun 8, 2026
But this way we would never update the features, I think that the service provider should add new features to the interface, and a way to implement it, and give the oportunities to the other service providers to add those to their products, for me this is like the keyed feature
aradalvand commentedon Jun 8, 2026
That's an argument to never add any features to the standard DI abstractions, ever. It is a terrible argument.
AKA285066112 commentedon Jun 16, 2026