Skip to content

[API Proposal]: EmptyServiceProvider #120198

Closed

Description

@stephentoub

Background and motivation

Many codebases that work with DI find a need for returning an empty IServiceProvider, and end up defining their own internal implementation. We could simplify this by providing a singleton instance so they don't have to.

API Proposal

namespace Microsoft.Extensions.DependencyInjection;

public sealed class EmptyServiceProvider : IKeyedServiceProvider, IServiceProviderIsKeyedService
{
    public static EmptyServiceProvider Instance { get; }

    // explicit implementations of the interface methods:
    object? IKeyedServiceProvider.GetKeyedService(Type serviceType, object? serviceKey);
    object IKeyedServiceProvider.GetRequiredKeyedService(Type serviceType, object? serviceKey);
    object? IServiceProvider.GetService(Type serviceType);
    bool IServiceProviderIsKeyedService.IsKeyedService(Type serviceType, object? serviceKey);
    bool IServiceProviderIsService.IsService(Type serviceType);
}

API Usage

public void DoWork(IServiceProvider? services = null)
{
    services ??= EmptyServiceProvider.Instance;
    ...
}

Details (added by @svick)

The service provider would not be literally empty, it would provide the services that are built into ServiceProvider: IServiceProvider, IServiceScopeFactory, IServiceProviderIsService and IServiceProviderIsKeyedService.

Alternative Designs (edited by @svick)

We could hang the singleton off of some existing type, e.g.

namespace Microsoft.Extensions.DependencyInjection;

public partial class ServiceCollection : IServiceCollection
{
    public static IKeyedServiceProvider EmptyServiceProvider { get; }
}

but then it's hard to add more interface implementations in a discoverable way.

An alternative name for this type is NullServiceProvider, since it follows the null object pattern. But I think the name EmptyServiceProvider is more specific and it's also more common in existing implementations.

Risks

No response

Activity

  1. added this to the 11.0.0 milestone on Sep 29, 2025
  2. added
    api-suggestion
    on Sep 29, 2025
  3. dotnet-policy-service commented on Sep 29, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-extensions-dependencyinjection
    See info in area-owners.md if you want to be subscribed.

  4. KalleOlaviNiemitalo commented on Sep 30, 2025

    @KalleOlaviNiemitalo

    Microsoft.Extensions.DependencyInjection.ServiceProvider has built-in services IServiceProvider, IServiceScopeFactory, IServiceProviderIsService, and IServiceProviderIsKeyedService that its IServiceProvider.GetService(Type) implementation provides even if they are not added to the IServiceCollection. Would EmptyServiceProvider do the same, or would it just return null?

  5. wvpm commented on Oct 19, 2025

    @wvpm

    Could you provide the context for the "need for returning an empty IServiceProvider"?
    Perhaps via links to one of the "Many codebases that work with DI".

  6. stephentoub commented on Oct 19, 2025

    @stephentoub
    MemberAuthor

    Could you provide the context for the "need for returning an empty IServiceProvider"? Perhaps via links to one of the "Many codebases that work with DI".

    https://grep.app/search?f.lang=C%23&q=class+EmptyServiceProvider

  7. self-assigned this
    on Feb 27, 2026
  8. added
    api-ready-for-review
    and removed
    api-suggestion
    on Apr 23, 2026
  9. KevinCathcart commented on Apr 28, 2026

    @KevinCathcart
    Contributor

    My one comment on this, is that I'm not sure if Empty is the right name. The roughly similar thing for logging we called NullLoggerFactory/NullLogger/NullLogger<T>. We also did Stream.Null. So NullServiceProvider would fit this pattern. That said, this is exactly the sort o thing that will be discussed in API review, and I don't feel strongly about the naming.

  10. KevinCathcart commented on Apr 28, 2026

    @KevinCathcart
    Contributor

    Looking at implementations in https://source.dot.net/, we do have a bunch called EmptyServiceProvider, and only one version called NullServiceProvider.

    We have one implementation that also supports IServiceScopeFactory (resolvable) and IServiceScope. Both implemented by returning this. I think we might want those interfaces too, to better approximate the behavior of new ServiceCollection().BuildServiceProvider(). I suppose in theory it could construct some other object that implements these types, but why? While the real ServiceProvider does that with IServiceProviderIsService and IServiceProviderIsKeyedService, but this proposal was already proposing just returning this for those, so that same logic makes sense for scopes too.

    This API shape would thus be:

    public sealed class EmptyServiceProvider : IKeyedServiceProvider, IServiceProviderIsKeyedService, IServiceScopeFactory, IServiceScope
    {
        public static EmptyServiceProvider Instance { get; }
    
        // explicit implementations of the interface methods/properties:
        object? IKeyedServiceProvider.GetKeyedService(Type serviceType, object? serviceKey);
        object IKeyedServiceProvider.GetRequiredKeyedService(Type serviceType, object? serviceKey);
        object? IServiceProvider.GetService(Type serviceType);
        bool IServiceProviderIsKeyedService.IsKeyedService(Type serviceType, object? serviceKey);
        bool IServiceProviderIsService.IsService(Type serviceType);
        bool IServiceScope IServiceScopeFactory.CreateScope();
        IServiceProvider IServiceScope.ServiceProvider {get;}
        void IDisposable.Dispose();
    }

    For reference purposes a valid 76 line implementation that seems to fully match the behavior of new ServiceCollection().BuildServiceProvider() (other than in terms of object identity and dispose checking) including edge cases like null ServiceKey, and returning empty IEnumerables:

    Expand to see implementation
    public sealed class EmptyServiceProvider :
        IKeyedServiceProvider,
        IServiceProviderIsKeyedService,
        IServiceScopeFactory,
        IServiceScope 
    {
        public static EmptyServiceProvider Instance { get; } = new ();
        
        private EmptyServiceProvider() {}
    
        object? IKeyedServiceProvider.GetKeyedService(Type serviceType, object? serviceKey)
            => GetKeyedSerivce(serviceType, serviceKey);
        
        private object? GetKeyedSerivce(Type serviceType, object? serviceKey)
        {
            if (serviceKey is null) return GetService(serviceType);
            if (IsEnumerableService(serviceType)) return Array.CreateInstance(serviceType.GenericTypeArguments[0], 0);
            return null;
        }
    
        object? IServiceProvider.GetService(Type serviceType)
            => GetService(serviceType);
        
        private object? GetService(Type serviceType)
        {
            if (IsBuiltInService(serviceType)) return this;
            if (IsEnumerableService(serviceType)) return CreateEmptyEnumerableService(serviceType);
            return null;
        }
    
        private static object CreateEmptyEnumerableService(Type serviceType)
            => Array.CreateInstance(serviceType.GenericTypeArguments[0], 0);
    
        bool IServiceProviderIsKeyedService.IsKeyedService(Type serviceType, object? serviceKey)
            => IsKeyedService(serviceType, serviceKey);
        
        private static bool IsKeyedService(Type serviceType, object? serviceKey)
            // This differs slightly from ServiceProvider to fix include a fix for #127537.
            => (serviceKey is null && IsBuiltInService(serviceType)) || IsEnumerableService(serviceType));
        
        bool IServiceProviderIsService.IsService(Type serviceType)
            => IsBuiltInService(serviceType) || IsEnumerableService(serviceType);
    
        private static bool IsBuiltInService(Type serviceType)
            => serviceType == typeof(IServiceProvider)
            || serviceType == typeof(IServiceScopeFactory) 
            || serviceType == typeof(IServiceProviderIsService)
            || serviceType == typeof(IServiceProviderIsKeyedService);
        
        private static bool IsEnumerableService(Type serviceType)
            => serviceType.IsGenericType && serviceType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
    
        IServiceScope IServiceScopeFactory.CreateScope() => this;
        
        IServiceProvider IServiceScope.ServiceProvider => this;
        
        void IDisposable.Dispose() {}
    
        object IKeyedServiceProvider.GetRequiredKeyedService(Type serviceType, object? serviceKey)
        {
            object? service = GetKeyedSerivce(serviceType, serviceKey);
            if (service is null)
            {
                if (serviceKey is null)
                {
                    ThrowHelper.ThrowInvalidOperationException_NoServiceRegistered(serviceType);
                }
                else
                {
                    ThrowHelper.ThrowInvalidOperationException_NoKeyedServiceRegistered(serviceType, serviceKey.GetType());
                }
            }
    
            return service;
        }
    }
  11. svick commented on Apr 30, 2026

    @svick
    Member

    @KevinCathcart I have added a note to the proposal about NullServiceProvider .

    Regarding IServiceProviderIsService and IServiceProviderIsKeyedService, I agree it makes sense to support them and I mentioned that in the proposal.

    But whether they're implemented by returning this is an implementation detail, so it should not be part of the API. If it's not part of the API, we can still implement it that way or change the implementation later. But if it is part of the API, it effectively has to be implemented that way. I don't see a reason to constrain the implementation like that.

  12. bartonjs commented on May 5, 2026

    @bartonjs
    Member

    Video

    • ServiceProvider.Empty was discussed as an alternative, but we leaned away from that given that ServiceProvider is sealed and the Empty instance would probably not want to return one.
    • So, looks good as proposed.
    namespace Microsoft.Extensions.DependencyInjection;
    
    public sealed class EmptyServiceProvider : IKeyedServiceProvider, IServiceProviderIsKeyedService
    {
        public static EmptyServiceProvider Instance { get; }
    
        // explicit implementations of the interface methods:
        object? IKeyedServiceProvider.GetKeyedService(Type serviceType, object? serviceKey);
        object IKeyedServiceProvider.GetRequiredKeyedService(Type serviceType, object? serviceKey);
        object? IServiceProvider.GetService(Type serviceType);
        bool IServiceProviderIsKeyedService.IsKeyedService(Type serviceType, object? serviceKey);
        bool IServiceProviderIsService.IsService(Type serviceType);
    }
  13. added
    api-approved
    and removed
    api-ready-for-review
    on May 5, 2026
  14. added a commit that references this issue on Jun 25, 2026
  15. locked and limited conversation to collaborators on Jul 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-Extensions-DependencyInjection

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions