container icon indicating copy to clipboard operation
container copied to clipboard

ChildContainers share the build strategy which results in unexpected behavior

Open RonHeck opened this issue 6 years ago • 0 comments

Description

Creating a child container and add a builder strategy by an extension will add the strategy to the strategy chain of the root container. This also effects the build chain of other child containers within the hierarchy and also effects resolving of types from the root container. This leads to unpredictable results when resolving types to instances.

To Reproduce

Please provide UnitTest in the form of:

using System;
using System.Linq;
using NUnit.Framework;
using Unity;
using Unity.Builder;
using Unity.Extension;
using Unity.Resolution;
using Unity.Strategies;

namespace Tests
{
    [TestFixture]
    public class ChildContainerTest
    {
        private class MagicNumberExtension : UnityContainerExtension
        {
            private readonly MagicNumberExtensionBuildStrategy _buildStrategy;

            /// <summary>
            ///     Creates a new instance of <see cref="MagicNumberExtension" />.
            /// </summary>
            public MagicNumberExtension(int magicNumber)
            {
                _buildStrategy = new MagicNumberExtensionBuildStrategy(magicNumber);
            }

            #region Members

            protected override void Initialize()
            {
                Context.Strategies.Add(_buildStrategy, UnityBuildStage.PreCreation);
            }

            #endregion

            #region Nested type: MagicNumberExtensionBuildStrategy

            private class MagicNumberExtensionBuildStrategy : BuilderStrategy
            {
                private readonly int _number;

                /// <summary>
                ///     Creates a new instance of <see cref="MagicNumberExtensionBuildStrategy" />.
                /// </summary>
                public MagicNumberExtensionBuildStrategy(int number)
                {
                    _number = number;
                }

                #region Members

                public override void PreBuildUp(ref BuilderContext context)
                {
                    var overrides = context.Overrides ?? Array.Empty<ResolverOverride>();
                    context.Overrides = overrides.Append(new DependencyOverride<int>(_number)).ToArray();
                    base.PreBuildUp(ref context);
                }

                #endregion
            }

            #endregion
        }

        private class TestType
        {
            /// <summary>
            ///     Creates a new instance of <see cref="TestType" />.
            /// </summary>
            public TestType(int magicNumber)
            {
                MagicNumber = magicNumber;
            }

            public int MagicNumber { get; }

            #region Members

            public override string ToString()
            {
                return $"TestType with magic number {MagicNumber}";
            }

            #endregion
        }

        [Test]
        public void Should_Create_Instance_With_Container_Specific_Build_Chain()
        {
            //***** arrange *****
            var coreContainer = new UnityContainer() as IUnityContainer;
            var childContainer1 = coreContainer.CreateChildContainer();
            childContainer1.AddExtension(new MagicNumberExtension(1));
            var childContainer2 = coreContainer.CreateChildContainer();
            childContainer2.AddExtension(new MagicNumberExtension(2));

            //***** act *****
            var testTypeFromChildContainer1 = childContainer1.Resolve<TestType>();
            var testTypeFromChildContainer2 = childContainer2.Resolve<TestType>();

            //***** assert *****
            TestContext.WriteLine(testTypeFromChildContainer1.ToString());
            TestContext.WriteLine(testTypeFromChildContainer2.ToString());

            Assert.That(testTypeFromChildContainer1.MagicNumber,
                Is.Not.EqualTo(testTypeFromChildContainer2.MagicNumber));
        }
    }
}

Additional context

Also disposing a child container does not provide any support to remove the registered builder strategy, even the abstract extension definition provides a virtual method "Remove". This may is fixed by https://github.com/unitycontainer/container/issues/227 but does not solve the issue of a global used build chain in container hierarchy.

My scenario: I have an application with a set of root services of an hosting environment registered within the root container. The user then opens a file that loads a component with an own bootstrapping. This bootstrapping creates the context, the component lives in. Therefore the context creates a child container from the environenmt container. All services registered within the child container are specific to the context and should only live until the context ist disposed (disposes the child container). The context also adds an extension to the child container that provides a context related builder strategy and has a configuration. When the user opens a second file the for this context created container resolves using the builder strategy from file 1 instead of the file 2. Also disposing the context of file 1 will cleanup all from child container 1 but not remove the builder strategy from the build chain. So finally I have a memory leak here.

RonHeck avatar Sep 04 '20 07:09 RonHeck