Skip to content

Nested injections are not in the correct scope #89

@Naun

Description

@Naun

Hi,

I need your help to understand if the following behavior is the expected one or if there is a trick to make it work. It seems that when there are nested dependency injections, the scope registrations are not taken into account. To make it clearer, I was expecting this test to pass, but it does not. It is failing to the last assertion:

[TestMethod]
public void NestedInjection_CreateChildContainer()
{
    IUnityContainer unityContainer = new UnityContainer();
    var serviceCollection = new ServiceCollection();
    serviceCollection.AddScoped<DbContext>(p => new DbContext());
    serviceCollection.AddScoped<Repository>(p => new Repository(p.GetService<DbContext>()));
    serviceCollection.BuildServiceProvider(unityContainer);

    // Creating a child container via unity
    var repositoryInstance1 = unityContainer.CreateChildContainer().Resolve<Repository>();
    var repositoryInstance2 = unityContainer.CreateChildContainer().Resolve<Repository>();

    // Instances of repository should be different
    Assert.AreNotEqual(repositoryInstance1.GetHashCode(), repositoryInstance2.GetHashCode());

    // Instances of dbcontext should be different
    Assert.AreNotEqual(repositoryInstance1.Context.GetHashCode(), repositoryInstance2.Context.GetHashCode());
}

My question is: does unity container creates a new scope when creating a child container?

Full test class:
NestedInjectionTests.log

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