Skip to content

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

@anlampe

Description

@anlampe

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions