JasperFx / lamar

Fast Inversion of Control Tool and Successor to StructureMap
https://jasperfx.github.io/lamar
MIT License
568 stars 119 forks source link

Does nested container service can not override parent #166

Closed johnLwith closed 5 years ago

johnLwith commented 5 years ago
        [Fact]
        public void Lamar_Should_Ok()
        {
            var container = new Container(_ =>
            {
                _.Injectable<IExecutionContext>();
                _.For<IExecutionContext>().Use<ExecutionContext1>();
            });

            Assert.Equal(typeof(ExecutionContext1), container.GetInstance<IExecutionContext>().GetType());
            var nested = container.GetNestedContainer();
            Assert.Equal(typeof(ExecutionContext1), nested.GetInstance<IExecutionContext>().GetType());
            nested.Inject(typeof(IExecutionContext), new ExecutionContext2(), true);

            var excepted1 = nested.GetInstance<IExecutionContext>();

           // Oops!!! excepted1 always shows ExecutionContext1
            Assert.Equal(typeof(ExecutionContext2), nested.GetInstance<IExecutionContext>().GetType());
        }
jeremydmiller commented 5 years ago

@chinaniit Your usage is a little bit off. The call to _.For<IExecutionContext>().Use<ExecutionContext1>(); overwrites the injectable registration. The following code works:

    public class Bug_166_injectable
    {
        public interface IExecutionContext{}
        public class ExecutionContext1 : IExecutionContext{}
        public class ExecutionContext2 : IExecutionContext{}

        [Fact]
        public void Lamar_Should_Ok()
        {
            var container = new Container(_ =>
            {
                // This is the ONLY registration you need
                _.Injectable<IExecutionContext>();
            });

            // If you need a value in the root container
            container.Inject<IExecutionContext>(new ExecutionContext1());

            container.GetInstance<IExecutionContext>()
                .ShouldBeOfType<ExecutionContext1>();

            var nested = container.GetNestedContainer();

            // Gotta do this too
            var nestedContext = new ExecutionContext2();
            nested.Inject(typeof(IExecutionContext), nestedContext, true);

            nested.GetInstance<IExecutionContext>()
                .ShouldBeSameAs(nestedContext);
        }
    }
johnLwith commented 5 years ago

@jeremydmiller Thanks for you reply.