seesharper / LightInject.Microsoft.DependencyInjection

Implements Microsoft.Extensions.DependencyInjection.Abstraction
MIT License
46 stars 13 forks source link

Different behavior between LightInjectServiceProvider and Microsoft.Extensions.DependencyInjection.ServiceProvider regarding resolving IServiceProvider #169

Open anlampe opened 3 years ago

anlampe commented 3 years ago

The LightInjectServiceProvider shows a different bahvior than the Microsoft.Extensions.DependencyInjection.ServiceProvider regarding resolving IServiceProvider.

I've created a test case which hopefully clarifies the desired behavior:

using System;
using LightInject;
using LightInject.Microsoft.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

public class ServiceProviderTest
{
    public class Service { }

    [Fact]
    public void ShouldBeRegisteredPerScopeAndContainItself()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddScoped<Service>();

        var container = new ServiceContainer(ContainerOptions.Default.WithMicrosoftSettings());

        var serviceProvider = container.CreateServiceProvider(serviceCollection);
        //var serviceProvider = serviceCollection.BuildServiceProvider();

        using var scope = serviceProvider.CreateScope();

        var scopeServiceProvider = scope.ServiceProvider.GetRequiredService<IServiceProvider>();

        Assert.Equal(scopeServiceProvider, scope.ServiceProvider);
        Assert.Equal(scopeServiceProvider.GetRequiredService<Service>(), scope.ServiceProvider.GetRequiredService<Service>());
    }
}

If you uncomment the line var serviceProvider = serviceCollection.BuildServiceProvider(); which uses the Microsoft.Extensions.DependencyInjection.ServiceProvider you will see the test passes.

Is there a way to change the behavior of the LightInjectServiceProvider accordingly?

Besides that, thank you for your great work!