Skip to content

Parameter resolution in hierarchies #198

@ENikS

Description

@ENikS

Description

With addition of 'Smart' selection Unity v5 introduced a bug. When resolving parameters for constructor or methods it resolves these from container used to receive request instead of container where type is registered

To Reproduce

Consider this type and registration:

public class TestType
{
    public TestType(IUnityContainer container)
    {
        Container = container;
    }
    public IUnityContainer Container { get; }
}


[TestMethod]
public void TestCase()
{
    var container = new UnityContainer()
                       .RegisterType<TestType>();
    var child = container.CreateChildContainer();

    var res0 = container.Resolve<TestType>();
    var res1 = child .Resolve<TestType>();

   Assert.AreEqual(res0.Container, res1.Container)
}

When v5 resolves the type from these two containers, the instance of the container provided to the constructor is not the same. If resolved from the root, it provides the root container. But when resolved from the child container, instead of supplying the reference of the container where the type is registered, it provides child container pointer instead.

The problem with this behavior is with availability of resolved instances after child container has been disposed.

Solution

To solve this issue Unity Container should resolve all the dependencies from the same container where the type is registered. In other words: If type registered at the root container and is being resolved from child container, all parameters are resolved at the container of registration (the root).

This will only apply to the explicit registrations, the ones you did with RegisterType(...). Unregistered types will have no scope associated with it.

Impact

This fix will change behavior from v5.x.
Users migrating from v4.0.1 will not be affected.

Metadata

Metadata

Assignees

Labels

Enhancement 🔨Improvement of existing features

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions