Skip to content

Inconsistent behavior using Unity vs Microsoft.Extensions.DependencyInjection #96

@CodeBlanch

Description

@CodeBlanch

Greetings!

This issue has been raised in a project I work on: open-telemetry/opentelemetry-dotnet#5537

Seems there is a behavior difference between how Unity handles the IServiceProvider.GetServices extension vs how Microsoft.Extensions.DependencyInjection does it.

This code using Microsoft.Extensions.DependencyInjection does NOT throw:

var mseServices = new ServiceCollection();

using var mseServiceProvider = ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(mseServices);
var mseFoundServices = mseServiceProvider.GetServices<SomeService>();
if (mseFoundServices.Any())
{
    throw new NotSupportedException("Found SomeService registrations in MSE"); // Not thrown when executed
}

This code using Unity.Microsoft.DependencyInjection does throw:

var mseServices = new ServiceCollection();

var unityServiceProvider = ServiceProviderExtensions.BuildServiceProvider(mseServices);
var unityFoundServices = unityServiceProvider.GetServices<SomeService>();
if (unityFoundServices.Any())
{
    throw new NotSupportedException("Found SomeService registrations in Unity"); // Thrown with executed
}

If I swap SomeService to an interface (eg ISomeService) then the behavior is consistent. But shouldn't it be consistent for both cases? From Unity's perspective, users should be able to swap in Unity over Microsoft.Extensions.DependencyInjection and not have to worry about subtle behavioral differences like this causing issues in random libraries, no?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions