Skip to content

Dependency Injection of Open Generics via factory #41050

Open

Description

@wvpm

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:

  1. 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.
  2. 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:

  1. Programmers using Microsoft.Extensions.DependencyInjection should update their code, resulting in extra work.
  2. The obsolete code should eventually be removed from Microsoft.Extensions.DependencyInjection, resulting in extra work.

Activity

  1. added
    api-suggestion
    on Aug 19, 2020
  2. added
    untriaged
    on Aug 19, 2020
  3. changed the title [-]Dependency Injection[/-] [+]Dependency Injection of Open Generics via factory[/+] on Aug 19, 2020
  4. wvpm commented on Aug 19, 2020

    @wvpm
    Author

    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.

            private ServiceCallSite TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, int slot)
            {
                if (serviceType == descriptor.ServiceType)
                {
                    ServiceCallSite callSite;
                    var lifetime = new ResultCache(descriptor.Lifetime, serviceType, slot);
                    if (descriptor.ImplementationInstance != null)
                    {
                        callSite = new ConstantCallSite(descriptor.ServiceType, descriptor.ImplementationInstance);
                    }
    +                else if (descriptor.TypedImplementationFactory != null)
    +                {
    +                    callSite = new FactoryCallSite(lifetime, descriptor.ServiceType, provider => descriptor.TypedImplementationFactory(provider, serviceType));
    +                }
                    else if (descriptor.ImplementationFactory != null)
                    {
                        callSite = new FactoryCallSite(lifetime, descriptor.ServiceType, descriptor.ImplementationFactory);
                    }
                    else if (descriptor.ImplementationType != null)
                    {
                        callSite = CreateConstructorCallSite(lifetime, descriptor.ServiceType, descriptor.ImplementationType, callSiteChain);
                    }
                    else
                    {
                        throw new InvalidOperationException("Invalid service descriptor");
                    }
    
                    return callSite;
                }
    
                return null;
            }
            private ServiceCallSite TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation)
            {
                if (serviceType.IsConstructedGenericType &&
                    serviceType.GetGenericTypeDefinition() == descriptor.ServiceType)
                {
    +                var lifetime = new ResultCache(descriptor.Lifetime, serviceType, slot);
    +                if (descriptor.TypedImplementationFactory != null)
    +                {
    +                    Type closedServiceType;
    +                    try
    +                    {
    +                        closedServiceType = descriptor.ServiceType.MakeGenericType(serviceType.GenericTypeArguments);
    +                    }
    +                    catch (ArgumentException)
    +                    {
    +                        if (throwOnConstraintViolation)
    +                        {
    +                            throw;
    +                        }
    +
    +                        return null;
    +                    }
    +                    return new FactoryCallSite(lifetime, descriptor.ServiceType, provider =>  descriptor.TypedImplementationFactory(provider, closedServiceType));
    +                }
    +
                    Debug.Assert(descriptor.ImplementationType != null, "descriptor.ImplementationType != null");
    -                var lifetime = new ResultCache(descriptor.Lifetime, serviceType, slot);
                    Type closedType;
                    try
                    {
                        closedType = descriptor.ImplementationType.MakeGenericType(serviceType.GenericTypeArguments);
                    }
                    catch (ArgumentException)
                    {
                        if (throwOnConstraintViolation)
                        {
                            throw;
                        }
    
                        return null;
                    }
    
                    return CreateConstructorCallSite(lifetime, serviceType, closedType, callSiteChain);
                }
    
                return null;
            }
  5. eerhardt commented on Aug 19, 2020

    @eerhardt
    Member

    I lack the rights to push a branch to this repository, so I cannot create a pull request myself.

    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.

  6. carusology commented on Aug 20, 2020

    @carusology

    Unless the stance of Microsoft here, here or here changed, this isn't happening.

    A good summary statement from @pakrym (Source):

    We haven't broken other service provider implementation since 1.0 and this feature is certainly not worth it. What it's trying to accomplish already exists in other providers

    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.

  7. wvpm commented on Aug 20, 2020

    @wvpm
    Author

    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.

  8. added this to the Future milestone on Aug 20, 2020
  9. removed
    untriaged
    on Aug 20, 2020
  10. davidfowl commented on Aug 23, 2020

    @davidfowl
    Member

    .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 😄

  11. wvpm commented on Aug 24, 2020

    @wvpm
    Author

    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.

  12. davidfowl commented on Aug 24, 2020

    @davidfowl
    Member

    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

  13. dazinator commented on Sep 24, 2020

    @dazinator

    I am creating a library to provide a "child container" feature for the native MS ServiceProvider but I have hit this problem with respect to singleton 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:

    Dazinator.Extensions.DependencyInjection.Tests.ChildServiceProvider.GenericHostTests.Options_WorksInChildContainers(args: [""])
       Source: GenericHost.cs line 23
       Duration: 269 ms
    
     > Message: 
        System.NotSupportedException : Open generic types registered as singletons in the parent container are not supported when using child containers: 
        ServiceType: Microsoft.Extensions.Options.IOptions`1
        ServiceType: Microsoft.Extensions.Options.IOptionsMonitor`1
        ServiceType: Microsoft.Extensions.Options.IOptionsMonitorCache`1
        ServiceType: Microsoft.Extensions.Logging.ILogger`1
        ServiceType: Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfiguration`1
    

    The issue (as already described) is that when a singleton open generic descriptor 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 partly solve the problem - enabling me to do as @wvpm suggested:

    IServiceProvider parentServiceProvider = GetParentServiceProvider();
    IServiceCollection childServices= GetChildServiceCollection();
    
    // for each of the singleton open generic descriptors registered in the parent, add them to the child but re-point the instance to be sourced from the parent container as we want to keep it a true singleton. 
    childServices.Add(new ServiceDescriptor(parentDescriptor.ServiceType , (IServiceProvider provider, Type requestedType) => parentServiceProvider.GetRequiredService(requestedType))
    

    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?

  14. 51 remaining items

  15. davidfowl commented on Jun 5, 2025

    @davidfowl
    Member

    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

  16. Alxandr commented on Nov 24, 2025

    @Alxandr
    Contributor

    Another really neat thing this would enable would be registering "self-factories".

    Example:

    public interface IConstructable<TSelf> where TSelf : IConstructable<TSelf> 
    {
        public static abstract TSelf Construct(ISomeService service);
    }
    
    // registered as
    services.AddSingleton(typeof(IConstructable<>), (s, type) => FactoryMethod.MakeGeneric(type).Invoke(s.GetRequiredService<ISomeService>()));

    I tried a similar pattern for metrics in services:

    public partial class MyService
    {
        public MyService(IMetrics<Metrics> metrics) { _metrics = metrics.Self; }
    
        // similar to ILogger<T>, this IMetrics<Metrics> does not need to be public or explicitly registered
        private class Metrics : IMetrics<Metrics>
        { // metric stuff goes here
        }
    
        private static partial class Log
        {  // logging stuffs goes here
        }
    }

    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.

  17. rosebyte commented on Feb 12, 2026

    @rosebyte
    Member

    Triage: this is a feature gap compared to other frameworks, we should consider implementing in future.

  18. CoreDX9 commented on Feb 26, 2026

    @CoreDX9

    I have a derivative version that implements this feature. If interested, I can organize it into a PR.
    CoreDX.Extensions.DependencyInjection

  19. cincuranet commented on Feb 26, 2026

    @cincuranet
    Contributor

    @CoreDX9 Sure. But we need to first go through API review. Are you up for proposing something and work on refining it (if needed)?

  20. CoreDX9 commented on Mar 11, 2026

    @CoreDX9

    @cincuranet Yes, I'm sure.
    Implementing this feature is not difficult. Just need FactoryCallSite to support Func<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.

  21. luizfbicalho commented on May 2, 2026

    @luizfbicalho

    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?

  22. CaptaiNiveau commented on May 14, 2026

    @CaptaiNiveau

    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:

    services.AddKeyedScoped(typeof(IRepository<>), "ref", (provider, o, type) => refServiceProvider.GetRequiredService(type))

    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!

  23. self-assigned this
    on May 26, 2026
  24. rosebyte commented on Jun 8, 2026

    @rosebyte
    Member

    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).

  25. removed their assignment
    on Jun 8, 2026
  26. luizfbicalho commented on Jun 8, 2026

    @luizfbicalho

    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

  27. aradalvand commented on Jun 8, 2026

    @aradalvand

    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).

    That's an argument to never add any features to the standard DI abstractions, ever. It is a terrible argument.

  28. AKA285066112 commented on Jun 16, 2026

    @AKA285066112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-Extensions-DependencyInjection

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions