Пример #1
0
        public void nested_container_disposal()
        {
            var container = new Container(_ =>
            {
                // A SingletonThing scoped service
                _.ForSingletonOf <IColorCache>().Use <ColorCache>();

                // A transient scoped service
                _.For <IColor>().Use <Green>();

                // An AlwaysUnique scoped service
                _.For <Purple>().AlwaysUnique();
            });

            ColorCache singleton    = null;
            Green      nestedGreen  = null;
            Blue       nestedBlue   = null;
            Purple     nestedPurple = null;

            using (var nested = container.GetNestedContainer())
            {
                // SingletonThing's are really built by the parent
                singleton = nested.GetInstance <IColorCache>()
                            .ShouldBeOfType <ColorCache>();

                nestedGreen = nested.GetInstance <IColor>()
                              .ShouldBeOfType <Green>();


                nestedBlue = nested.GetInstance <Blue>();

                nestedPurple = nested.GetInstance <Purple>();
            }

            // Transients created by the Nested Container
            // are disposed
            nestedGreen.WasDisposed.ShouldBeTrue();
            nestedBlue.WasDisposed.ShouldBeTrue();

            // Unique's created by the Nested Container
            // are disposed
            nestedPurple.WasDisposed.ShouldBeTrue();


            // NOT disposed because it's owned by
            // the parent container
            singleton.WasDisposed.ShouldBeFalse();
        }
Пример #2
0
        public void build_nested_container_with_defaults()
        {
            var container = new Container(_ =>
            {
                _.For <Blue>().Use <Blue>();
                _.For <IWidget>().Use <DefaultWidget>();
                _.For <Rule>().Use <ARule>();
            });

            var nestedWidget = new AWidget();
            var nestedBlue   = new Blue();
            var arguments    = new TypeArguments().Set(nestedBlue).Set <IWidget>(nestedWidget);

            var nested = container.GetNestedContainer(arguments);

            nested.GetInstance <IWidget>().ShouldBeTheSameAs(nestedWidget);
            nested.GetInstance <Blue>().ShouldBeTheSameAs(nestedBlue);

            // fallback to the parent w/ no defaults
            nested.GetInstance <Rule>().ShouldBeOfType <ARule>();

            // main container is not corrupted by the nested registrations
            container.GetInstance <IWidget>().ShouldBeOfType <DefaultWidget>();
        }