microsoft-dependency-injection
microsoft-dependency-injection copied to clipboard
Inconsistent behavior using Unity vs Microsoft.Extensions.DependencyInjection
Greetings!
This issue has been raised in a project I work on: https://github.com/open-telemetry/opentelemetry-dotnet/issues/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?