Esempio n. 1
0
        /// <summary>
        /// Create a new instance of IoCUnitContainer
        /// </summary>
        public IoCUnityContainer()
        {
            _ContainersDictionary = new Dictionary <string, IUnityContainer>();

            //Create root container
            IUnityContainer rootContainer = new UnityContainer();

            rootContainer.AddNewExtension <Interception>();

            _ContainersDictionary.Add("RootContext", rootContainer);

            //Create container for real context, child of root container
            IUnityContainer realAppContainer = rootContainer.CreateChildContainer();

            _ContainersDictionary.Add("RealAppContext", realAppContainer);

            //Create container for testing, child of root container
            IUnityContainer fakeAppContainer = rootContainer.CreateChildContainer();

            _ContainersDictionary.Add("FakeAppContext", fakeAppContainer);


            ConfigureRootContainer(rootContainer);
            ConfigureRealContainer(realAppContainer);
            ConfigureFakeContainer(fakeAppContainer);
        }
        /// <summary>
        /// Create a new instance of IoCUnitContainer
        /// </summary>
        public IoCUnityContainer()
        {
            _ContainersDictionary = new Dictionary <string, IUnityContainer>();

            //Create root container
            IUnityContainer rootContainer = new UnityContainer();

            _ContainersDictionary.Add("RootContext", rootContainer);

            //Create container for real context, child of root container
            IUnityContainer realAppContainer = rootContainer.CreateChildContainer();

            _ContainersDictionary.Add("RealAppContext", realAppContainer);

            //Create container for testing, child of root container
            IUnityContainer fakeAppContainer = rootContainer.CreateChildContainer();

            _ContainersDictionary.Add("FakeAppContext", fakeAppContainer);


            ConfigureRootContainer(rootContainer);
            ConfigureRealContainer(realAppContainer);

            //(CDLTLL) Commented - Probable Dependecies Errors in Windows Azure Cloud (It works in Local Azure-Fabric)
            // At the moment it is ok, as Moles and fake container is not needed in Azure Production
            //ConfigureFakeContainer(fakeAppContainer);
        }
Esempio n. 3
0
        public UnityIoC(string nameDefault)

        {
            //Create root container

            _containersDictionary = new Dictionary <string, IUnityContainer>();
            IUnityContainer rootUibasoftContainer = new UnityContainer();

            _containersDictionary.Add(RootContext, rootUibasoftContainer);

            //Create container for real context, child of root container
            var realAppContainer = rootUibasoftContainer.CreateChildContainer();

            _containersDictionary.Add(RealAppContext, realAppContainer);

            //Create container for testing, child of root container
            var fakeAppContainer = rootUibasoftContainer.CreateChildContainer();

            _containersDictionary.Add(TestAppContext, fakeAppContainer);

            var defaultContainerConfigurationName = nameDefault;


            if (!_containersDictionary.ContainsKey(defaultContainerConfigurationName.ToLower()))
            {
                throw new InvalidOperationException(LocalizedText.ErrorDefaultContainerContainsKey);
            }

            _unityDefaulContainer = _containersDictionary[defaultContainerConfigurationName];
        }
Esempio n. 4
0
        private IActionTreeNodePresenter ActionTreeNodePresenterFactory(IAction arg)
        {
            IUnityContainer childContainer = _container.CreateChildContainer();

            childContainer.RegisterInstance(arg);
            return(childContainer.Resolve <IActionTreeNodePresenter>());
        }
Esempio n. 5
0
        public void Test9()
        {
            var c = new UnityContainer();



            var s1 = new ServiceCollection().AddOptions();
            var s2 = new ServiceCollection().AddOptions();


            s1.AddSingleton <ITest1, Test1>();
            s2.AddSingleton <ITest1, Test1>();
            s1.AddSingleton(typeof(IMygenericTest <>), typeof(MyGenericTest <>));
            s2.AddSingleton(typeof(IMygenericTest <>), typeof(MyGenericTest <>));


            var sp1 = s1.BuildServiceProvider(c.CreateChildContainer());

            var t1 = sp1.GetRequiredService <ITest1>();

            var sp2 = s2.BuildServiceProvider(c.CreateChildContainer());
            var t2  = sp2.GetRequiredService <ITest1>();

            //Works for above, but not below


            Assert.AreNotSame(t2, t1);
            Assert.AreNotSame(t2.GetHashCode(), t1.GetHashCode());

            var h1 = sp1.GetRequiredService <IMygenericTest <int> >();
            var h2 = sp2.GetRequiredService <IMygenericTest <int> >();

            Assert.IsNotNull(h1, "notnull");
            Assert.AreNotSame(h1, h2, "sameobj");
        }
Esempio n. 6
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                args = new[] { "10", "+", "20", "+", "30" };
            }

            using (var container = new UnityContainer())
            {
                Bootstrapper.SetupContainer(container);

                using (var childContainer = container.CreateChildContainer())
                {
                    Bootstrapper.SetupChildContainer(childContainer);

                    PerformCalculationAndWriteResult(args, childContainer);
                }

                using (var childContainer = container.CreateChildContainer())
                {
                    Bootstrapper.SetupChildContainer(childContainer);

                    PerformCalculationAndWriteResult(args, childContainer);
                }
            }
        }
Esempio n. 7
0
        public void Enumerable_SingletonServicesComeFromRootProvider()
        {
            using (IUnityContainer provider = new UnityContainer())
            {
                // Arrange
                provider.RegisterType <IService, EmailService>(new ContainerControlledLifetimeManager());

                EmailService disposableService1;
                EmailService disposableService2;

                // Act and Assert
                using (var scope = provider.CreateChildContainer())
                {
                    var service = scope.Resolve <IService>();
                    disposableService1 = (EmailService)service;
                    Assert.IsFalse(disposableService1.Disposed);
                }

                Assert.IsFalse(disposableService1.Disposed);

                using (var scope = provider.CreateChildContainer())
                {
                    var service = scope.Resolve <IService>();
                    disposableService2 = (EmailService)service;
                    Assert.IsFalse(disposableService2.Disposed);
                }

                Assert.IsFalse(disposableService2.Disposed);
                Assert.AreSame(disposableService1, disposableService2);
            }
        }
Esempio n. 8
0
        public static void Init(TestContext context)
        {
            var container = new UnityContainer();
            var config    = new SdkConfiguration("test", "test", "10.27.26.83");

            container.RegisterTypes(config);
            _childContainer1 = container.CreateChildContainer();
            _childContainer2 = container.CreateChildContainer();
        }
Esempio n. 9
0
        public void ContainerControlledOpenGenericInParentResolvesProperlyInChild()
        {
            IUnityContainer parentContainer = new UnityContainer()
                                              .RegisterType(typeof(ISomeInterface <>), typeof(MyTypeImplementingSomeInterface <>), new ContainerControlledLifetimeManager());

            var childOneObject = parentContainer.CreateChildContainer().Resolve <ISomeInterface <string> >();
            var childTwoObject = parentContainer.CreateChildContainer().Resolve <ISomeInterface <string> >();

            Assert.AreSame(childOneObject, childTwoObject);
        }
Esempio n. 10
0
        public static void TestContainerControlledLifetimeManager()
        {
            IExample example;

            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType(typeof(IExample), typeof(Example),
                                       new ContainerControlledLifetimeManager());

                IUnityContainer firstSub  = null;
                IUnityContainer secondSub = null;

                try
                {
                    firstSub  = container.CreateChildContainer();
                    secondSub = container.CreateChildContainer();

                    // all containers share same instance
                    // each resolve returns same instance
                    firstSub.Resolve <IExample>().SayHello();

                    // run one resolving in other thread and still receive same instance
                    Thread thread = new Thread(
                        () => secondSub.Resolve <IExample>().SayHello());
                    thread.Start();

                    container.Resolve <IExample>().SayHello();
                    example = container.Resolve <IExample>();
                    thread.Join();
                }
                finally
                {
                    if (firstSub != null)
                    {
                        firstSub.Dispose();
                    }
                    if (secondSub != null)
                    {
                        secondSub.Dispose();
                    }
                }
            }

            try
            {
                // exception - instance has been disposed with container
                example.SayHello();
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
Esempio n. 11
0
        public void Given_an_open_generic_registration_with_a_container_controlled_lifetime_then_resolving_twice_on_different_children_containers_should_return_the_same_instance()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterType(typeof(IOpenGenericSample <,>), typeof(OpenGenericSample <,>), new ContainerControlledLifetimeManager());

            var sampleOne = container.CreateChildContainer().Resolve <IOpenGenericSample <int, int> >();
            var sampleTwo = container.CreateChildContainer().Resolve <IOpenGenericSample <int, int> >();

            Assert.AreSame(sampleOne, sampleTwo);
            Assert.AreEqual(sampleOne.GetHashCode(), sampleTwo.GetHashCode());
        }
Esempio n. 12
0
        public static void TestHierarchicalLifetimeManager()
        {
            IExample example;

            using (IUnityContainer container = new UnityContainer())
            {
                container.RegisterType(typeof(IExample), typeof(Example),
                                       new HierarchicalLifetimeManager());

                IUnityContainer firstSub  = null;
                IUnityContainer secondSub = null;

                try
                {
                    firstSub  = container.CreateChildContainer();
                    secondSub = container.CreateChildContainer();

                    // each subcontainer has its own instance
                    firstSub.Resolve <IExample>().SayHello();
                    secondSub.Resolve <IExample>().SayHello();
                    container.Resolve <IExample>().SayHello();
                    example = firstSub.Resolve <IExample>();
                }
                finally
                {
                    if (firstSub != null)
                    {
                        firstSub.Dispose();
                    }
                    if (secondSub != null)
                    {
                        secondSub.Dispose();
                    }
                }
            }

            try
            {
                // exception - instance has been disposed with container
                example.SayHello();
            }
            catch (ObjectDisposedException ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
Esempio n. 13
0
        public void Test13()
        {
            //  ReplaceTest.Install();

            var c  = new UnityContainer();
            var cc = c.CreateChildContainer();

            cc.AddNewExtension <IOptionsExtension> ();

            var sc = new ServiceCollection();

            sc.AddIdentityServer(o =>
            {
                o.Events.RaiseErrorEvents = true;
            });

            var sp = sc.BuildServiceProvider();


            var test = sp.GetService <IdentityServerOptions>();

            Assert.IsNotNull(test); //Passes


            var sp1 = sc.BuildServiceProvider(cc.CreateChildContainer());


            var test1 = sp1.GetService <IdentityServerOptions>();

            Assert.IsNotNull(test1);
        }
Esempio n. 14
0
        public IUnityContainer GetOxiteContainer()
        {
            IUnityContainer parentContainer = new UnityContainer();

            parentContainer
            .RegisterInstance(new AppSettingsHelper(ConfigurationManager.AppSettings))
            .RegisterInstance(RouteTable.Routes)
            .RegisterInstance(HostingEnvironment.VirtualPathProvider)
            .RegisterInstance("RegisterRoutesHandler", typeof(MvcRouteHandler));

            foreach (ConnectionStringSettings connectionString in ConfigurationManager.ConnectionStrings)
            {
                parentContainer.RegisterInstance(connectionString.Name, connectionString.ConnectionString);
            }

            parentContainer
            .RegisterType <ISiteService, SiteService>()
            .RegisterType <IPluginService, PluginService>()
            .RegisterType <IUserService, UserService>()
            .RegisterType <ITagService, TagService>()
            .RegisterType <IPostService, PostService>()
            .RegisterType <ITrackbackOutboundService, TrackbackOutboundService>()
            .RegisterType <IMessageService, MessageService>()
            .RegisterType <IPageService, PageService>()
            .RegisterType <IAreaService, AreaService>()
            .RegisterType <ILocalizationService, LocalizationService>()
            .RegisterType <ILanguageService, LanguageService>()
            .RegisterType <IActionInvoker, OxiteControllerActionInvoker>()
            .RegisterType <IFormsAuthentication, FormsAuthenticationWrapper>()
            .RegisterType <ISkinEngine, VirtualPathProviderSkinEngine>()
            .RegisterType <IViewEngine, OxiteViewEngine>()
            .RegisterType <IValidationService, ValidationService>()
            .RegisterType <IRegularExpressions, RegularExpressions>()
            .RegisterType <IValidator <Comment>, CommentValidator>()
            .RegisterType <IValidator <UserBase>, UserBaseValidator>()
            .RegisterType <IValidator <PostSubscription>, PostSubscriptionValidator>()
            .RegisterType <IValidator <User>, UserValidator>()
            .RegisterType <IValidator <Site>, SiteValidator>()
            .RegisterType <IValidator <Area>, AreaValidator>()
            .RegisterType <IValidator <Post>, PostValidator>()
            .RegisterType <IValidator <Page>, PageValidator>()
            .RegisterType <IRegisterRoutes, OxiteRoutes>(
                new InjectionConstructor(
                    new ResolvedParameter <RouteCollection>(),
                    new ResolvedParameter <AppSettingsHelper>(),
                    new ResolvedParameter <Site>(),
                    new ResolvedParameter <IAreaService>(),
                    new ResolvedParameter <Type>("RegisterRoutesHandler")
                    ));

            IUnityContainer oxiteContainer = parentContainer.CreateChildContainer();

            UnityConfigurationSection config = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            config.Containers.Default.Configure(oxiteContainer);

            oxiteContainer.RegisterInstance(oxiteContainer);

            return(oxiteContainer);
        }
Esempio n. 15
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                args = new[] { "10", "+", "20", "+", "30", "-", "12" };
            }

            using (var container = new UnityContainer())
            {
                Bootstrapper.SetupContainer(container);

                try
                {
                    PerformCalculation(args, container);
                }
                catch (Exception exception)
                {
                    // Since the Minus class is registered only in the child container
                    // the default expression cannot be evaluated on the root container
                    Console.WriteLine(exception);
                }

                using (var childContainer = container.CreateChildContainer())
                {
                    Bootstrapper.SetupChildContainer(childContainer);

                    PerformCalculation(args, childContainer);
                }
            }
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            //Driver driver = new Driver(new BMW());
            //driver.RunCar();

            var container = new UnityContainer().RegisterType <ICar, BMW>(new HierarchicalLifetimeManager());

            var childContainer = container.CreateChildContainer();

            var driver1 = container.Resolve <Driver>();

            driver1.RunCar();

            var driver2 = container.Resolve <Driver>();

            driver2.RunCar();

            var driver3 = childContainer.Resolve <Driver>();

            driver3.RunCar();

            var driver4 = childContainer.Resolve <Driver>();

            driver4.RunCar();
        }
Esempio n. 17
0
        private static void HierarchicalLifetimeManagerDemo()
        {
            Console.WriteLine("\nHierarchicalLifetimeManagerDemo() start");

            var container = new UnityContainer();

            container.RegisterType <ICar, BMW>(new HierarchicalLifetimeManager());
            container.RegisterType <ICarKey, BMWKey>(new HierarchicalLifetimeManager());

            var childContainer = container.CreateChildContainer();

            var driver1 = container.Resolve <Driver>();

            driver1.RunCar();

            var driver2 = container.Resolve <Driver>();

            driver2.RunCar();

            var driver3 = childContainer.Resolve <Driver>();

            driver3.RunCar();

            var driver4 = childContainer.Resolve <Driver>();

            driver4.RunCar();

            Console.WriteLine("HierarchicalLifetimeManagerDemo() stop\n");
        }
Esempio n. 18
0
        public void HierarchicalLifetimeManager_Child_Not_Equal_To_Parent()
        {
            // Create parent container
            IUnityContainer parentCtr = new UnityContainer();

            // Register type in parent container
            parentCtr.RegisterType <MyObject>(new HierarchicalLifetimeManager());

            // Create nested child container in parent container
            IUnityContainer childCtr = parentCtr.CreateChildContainer();

            MyObject parentObject1 = parentCtr.Resolve <MyObject>();
            MyObject parentObject2 = parentCtr.Resolve <MyObject>();

            Assert.That(parentObject2.GetHashCode(), Is.EqualTo(parentObject1.GetHashCode()), "paren1 != parent2");

            MyObject childObject = childCtr.Resolve <MyObject>();

            Assert.That(childObject.GetHashCode(), Is.Not.EqualTo(parentObject1.GetHashCode()), "child != parent");

            // Dispose child container
            childCtr.Dispose();

            // Dispose parent container
            parentCtr.Dispose();
        }
        public void NestedContainerOverrideInParentDoesNotReturnOverridenInChildAcrossCalls()
        {
            IToWhichDependent overrideValue = new Type2ToWhichDependent(222);

            IUnityContainer container      = new UnityContainer();
            IUnityContainer childContainer = container.CreateChildContainer();

            // Registering the parent default types.
            container.RegisterType <IDependingOnOtherType, Type1DependingOnOtherType>().RegisterType <IToWhichDependent, Type1ToWhichDependent>(new InjectionConstructor(111));

            // Overriding the default values for the parent container.
            Type1DependingOnOtherType parentResult = (Type1DependingOnOtherType)container.Resolve <IDependingOnOtherType>(new DependencyOverride(typeof(IToWhichDependent), overrideValue));
            // Resolving child container to the default type.
            Type1DependingOnOtherType childResult = (Type1DependingOnOtherType)childContainer.Resolve <IDependingOnOtherType>();

            // The parent overriden values should be reflected.
            Assert.IsInstanceOfType(parentResult.IToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.IsInstanceOfType(parentResult.OneMoreIToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.AreEqual <int>(parentResult.IToWhichDependent.X, 222);

            // The parent default registered type should be reflected, since there are no type registered exclusively for the child container.
            Assert.IsInstanceOfType(childResult.IToWhichDependent, typeof(Type1ToWhichDependent));
            Assert.IsInstanceOfType(childResult.OneMoreIToWhichDependent, typeof(Type1ToWhichDependent));
            Assert.AreEqual <int>(childResult.IToWhichDependent.X, 111);
        }
Esempio n. 20
0
        static void InitContainers()
        {
            /*
             * CREATE DICTIONARY
             */
            _containersDictionary = new Dictionary <string, IUnityContainer>();

            /*
             * CREATE CONTAINERS
             */
            //Create root container
            IUnityContainer rootContainer = new UnityContainer();

            _containersDictionary.Add("RootContext", rootContainer);

            //Create container for real context, child of root container
            var realAppContainer = rootContainer.CreateChildContainer();

            _containersDictionary.Add("RealAppContext", realAppContainer);

            //Create container for testing, child of root container
            //IUnityContainer fakeAppContainer = rootContainer.CreateChildContainer();
            //_containersDictionary.Add("FakeAppContext", fakeAppContainer);

            /*
             * CONFIGURE CONTAINERS
             */
            ConfigureRootContainer(rootContainer);

            //ConfigureRealContainer(realAppContainer);
            //ConfigureFakeContainer(fakeAppContainer);
        }
        public void ParentContainerResolvesParentNotChild()
        {
            IUnityContainer parent = new UnityContainer();
            IUnityContainer child  = parent.CreateChildContainer();

            Assert.AreSame(parent, parent.Resolve <IUnityContainer>());
        }
Esempio n. 22
0
        public CollectService()
        {
            var diContainer = new UnityContainer().CreateChildContainer();

            lock (ScheduleInitLock)
            {
                var scheduler = new Quartz.Impl.StdSchedulerFactory().GetScheduler();
                if (ScheduleController == null)
                {
                    SchedulerContainer   = diContainer.CreateChildContainer();
                    scheduler.JobFactory = new UnityJobFactory(SchedulerContainer);
                    ScheduleController   = new ScheduleController(scheduler);
                    ScheduleController.ReschedulingAlreadyExecuted = false;
                }

                diContainer.RegisterType <IDataProvider, DataProvider>(new ContainerControlledLifetimeManager());
                diContainer.RegisterType <ICollectRequestRepository, CollectRequestRepository>(new ContainerControlledLifetimeManager());
                diContainer.RegisterType <IProbeManager, ProbeManager>();
                diContainer.RegisterType <ICollectRequestAssembler, CollectRequestAssembler>(new ContainerControlledLifetimeManager());
                diContainer.RegisterType <ICollectPackageAssembler, CollectPackageAssembler>(new ContainerControlledLifetimeManager());
                diContainer.RegisterType <ICollectResultAssembler, CollectResultAssembler>(new ContainerControlledLifetimeManager());
                diContainer.RegisterType <IDefinitionDocumentFactory, DefinitionDocumentFactory>(new ContainerControlledLifetimeManager());
                diContainer.RegisterInstance <IScheduler>(scheduler);
                diContainer.RegisterInstance <IScheduleController>(ScheduleController);

                CollectController = diContainer.Resolve <CollectController>();
            }
        }
        public void DependencyOverrideWithNestedContainer()
        {
            IToWhichDependent defaultValue   = new Type1ToWhichDependent(111);
            IToWhichDependent overrideValue3 = new Type2ToWhichDependent(333);
            IToWhichDependent overrideValue4 = new Type2ToWhichDependent(444);

            IUnityContainer container      = new UnityContainer();
            IUnityContainer childContainer = container.CreateChildContainer();

            // Registering the parent default types.
            container.RegisterType <IDependingOnOtherType, Type1DependingOnOtherType>().RegisterType <IToWhichDependent, Type1ToWhichDependent>(new InjectionConstructor(111));
            // Registering the child default types.
            childContainer.RegisterType <IDependingOnOtherType, Type1DependingOnOtherType>().RegisterType <IToWhichDependent, Type1ToWhichDependent>(new InjectionConstructor(222));

            // Overriding the default values for the parent container.
            Type1DependingOnOtherType parentResult = (Type1DependingOnOtherType)container.Resolve <IDependingOnOtherType>(new DependencyOverride(typeof(IToWhichDependent), overrideValue3));
            // Overriding the default values for the child container.
            Type1DependingOnOtherType childResult = (Type1DependingOnOtherType)childContainer.Resolve <IDependingOnOtherType>(new DependencyOverride(typeof(IToWhichDependent), overrideValue4));

            // The parent overriden values should be reflected.
            Assert.IsInstanceOfType(parentResult.IToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.IsInstanceOfType(parentResult.OneMoreIToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.AreEqual <int>(parentResult.IToWhichDependent.X, 333);

            // The child overriden values should be reflected.
            Assert.IsInstanceOfType(childResult.IToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.IsInstanceOfType(childResult.OneMoreIToWhichDependent, typeof(Type2ToWhichDependent));
            Assert.AreEqual <int>(childResult.IToWhichDependent.X, 444);
        }
        public void ChildContainerResolvesChildNotParent()
        {
            IUnityContainer parent = new UnityContainer();
            IUnityContainer child  = parent.CreateChildContainer();

            Assert.AreSame(child, child.Resolve <IUnityContainer>());
        }
Esempio n. 25
0
        public void Test_CreateChildContainer_ChildAddsInstance_ExpectingChildCanResolveParentsRegistration()
        {
            var parentContainer = new UnityContainer();
            var i1Mock          = new Mock <II1>();

            i1Mock.Setup(i1 => i1.f1(1)).Returns(42);
            parentContainer.RegisterInstance(i1Mock.Object);

            //parent
            var i1Obj = parentContainer.Resolve <II1>();

            Assert.IsNotNull(i1Obj);
            Assert.AreEqual(0, i1Obj.f1(0));
            Assert.AreEqual(42, i1Obj.f1(1));

            //child
            IUnityContainer childContainer = parentContainer.CreateChildContainer();

            i1Obj = childContainer.Resolve <II1>();
            Assert.IsNotNull(childContainer.Resolve <II1>());
            Assert.AreEqual(0, i1Obj.f1(0));
            Assert.AreEqual(42, i1Obj.f1(1));

            //parent
        }
Esempio n. 26
0
        public void MoreChildContainers2()
        {
            UnityContainer parent = new UnityContainer();

            parent.RegisterType <ITemporary, Temp>("First", new HierarchicalLifetimeManager());

            UnityContainer child1 = (UnityContainer)parent.CreateChildContainer();

            child1.RegisterType <ITemporary, Temp>("First", new HierarchicalLifetimeManager());
            var result  = parent.Resolve <ITemporary>("First");
            var result1 = child1.Resolve <ITemporary>("First");

            Assert.AreNotEqual <int>(result.GetHashCode(), result1.GetHashCode());

            UnityContainer child2 = (UnityContainer)child1.CreateChildContainer();

            child2.RegisterType <ITemporary, Temp>("First", new HierarchicalLifetimeManager());
            var result2 = child2.Resolve <ITemporary>("First");

            Assert.AreNotEqual <int>(result.GetHashCode(), result2.GetHashCode());
            Assert.AreNotEqual <int>(result1.GetHashCode(), result2.GetHashCode());

            List <ITemporary> count = new List <ITemporary>(child2.ResolveAll <ITemporary>());

            Assert.AreEqual(1, count.Count);
        }
Esempio n. 27
0
        public void ChildParentRegisrationOverlapTest()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterInstance("str1", "string1");
            container.RegisterInstance("str2", "string2");

            IUnityContainer child = container.CreateChildContainer();

            child.RegisterInstance("str2", "string20");
            child.RegisterInstance("str3", "string30");

            var    childStrList  = child.ResolveAll <string>();
            var    parentStrList = container.ResolveAll <string>();
            string childString   = String.Empty;
            string parentString  = String.Empty;

            foreach (string str in childStrList)
            {
                childString = childString + str;
            }
            foreach (string str1 in parentStrList)
            {
                parentString = parentString + str1;
            }

            Assert.AreEqual <string>("string1string20string30", childString);
            Assert.AreEqual <string>("string1string2", parentString);
        }
        public void ResolveAll()
        {
            IUnityContainer root = new UnityContainer();
            object          o1   = new object();
            object          o2   = new object();

            root
            .RegisterInstance <object>("o1", o1)
            .RegisterInstance <object>(o1)
            .RegisterInstance <object>(root)
            .RegisterInstance <object>("o2", o2);

            var obj   = "child";
            var child = root.CreateChildContainer()
                        .RegisterInstance <object>(obj)
                        .RegisterInstance <object>(o1)
                        .RegisterInstance <object>("o2", obj);

            var results  = root.Resolve <object[]>();
            var results1 = child.Resolve <object[]>();

            Assert.IsNotNull(results);
            Assert.IsNotNull(results1);
            Assert.IsInstanceOfType(results, typeof(object[]));
        }
Esempio n. 29
0
        public void MoreChildContainers1()
        {
            UnityContainer parent = new UnityContainer();

            parent.RegisterType <ITemporary, Temp>("First");
            parent.RegisterType <ITemporary, Temp>("First");
            UnityContainer child1 = (UnityContainer)parent.CreateChildContainer();

            child1.RegisterType <ITemporary, Temp>("First");
            child1.RegisterType <ITemporary, Temp>("First");
            UnityContainer child2 = (UnityContainer)child1.CreateChildContainer();

            child2.RegisterType <ITemporary, Temp>("First");
            child2.RegisterType <ITemporary, Temp>("First");
            UnityContainer child3 = (UnityContainer)child2.CreateChildContainer();

            child3.RegisterType <ITemporary, Temp>("First");
            child3.RegisterType <ITemporary, Temp>("First");
            IUnityContainer child4 = child3.CreateChildContainer();

            child4.RegisterType <ITemporary, Temp>("First");
            ITemporary first = child4.Resolve <ITemporary>("First");

            child4.RegisterType <ITemporary, Temp>("First", new ContainerControlledLifetimeManager());
            List <ITemporary> count = new List <ITemporary>(child4.ResolveAll <ITemporary>());

            Assert.AreEqual(1, count.Count);
        }
Esempio n. 30
0
        public void Enumerable_ResolvesDifferentInstancesForOpenGenericsWhenResolvingEnumerable()
        {
            using (IUnityContainer provider = new UnityContainer())
            {
                // Arrange
                provider.RegisterType <IService, EmailService>();
                provider.RegisterType(typeof(IFoo <>), typeof(Foo <>), "1", new ContainerControlledLifetimeManager());
                provider.RegisterType(typeof(IFoo <>), typeof(Foo <>), "2", new ContainerControlledLifetimeManager());
                provider.RegisterType(typeof(IFoo <>), typeof(Foo <>), "3", new ContainerControlledLifetimeManager());

                using (var scope = provider.CreateChildContainer())
                {
                    var enumerable = scope.Resolve <IEnumerable <IFoo <IService> > >().ToArray();
                    var service    = scope.Resolve <IFoo <IService> >("3");

                    // Assert
                    Assert.AreEqual(3, enumerable.Length);
                    Assert.IsNotNull(enumerable[0]);
                    Assert.IsNotNull(enumerable[1]);
                    Assert.IsNotNull(enumerable[2]);

                    Assert.AreNotSame(enumerable[0], enumerable[1]);
                    Assert.AreNotSame(enumerable[1], enumerable[2]);
                    Assert.AreSame(service, enumerable[2]);
                }
            }
        }
        public void NamesRegisteredInParentAppearInChild()
        {
            UnityContainer parent = new UnityContainer();
            parent.RegisterType<ILogger, SpecialLogger>("special");

            IUnityContainer child = parent.CreateChildContainer();

            ILogger l = child.Resolve<ILogger>("special");

            Assert.IsInstanceOfType(l, typeof(SpecialLogger));
        }
Esempio n. 32
0
        public void ChildBuildsUsingParentsConfiguration()
        {
            UnityContainer parent = new UnityContainer();
            parent.RegisterType<ILogger, MockLogger>();

            IUnityContainer child = parent.CreateChildContainer();
            ILogger logger = child.Resolve<ILogger>();

            Assert.NotNull(logger);
            AssertExtensions.IsInstanceOfType(logger, typeof(MockLogger));
        }
Esempio n. 33
0
        public void ChangeInParentConfigurationIsReflectedInChild()
        {
            UnityContainer parent = new UnityContainer();
            parent.RegisterType<ILogger, MockLogger>();
            IUnityContainer child = parent.CreateChildContainer();

            ILogger first = child.Resolve<ILogger>();
            parent.RegisterType<ILogger, SpecialLogger>();
            ILogger second = child.Resolve<ILogger>();

            AssertExtensions.IsInstanceOfType(first, typeof(MockLogger));
            AssertExtensions.IsInstanceOfType(second, typeof(SpecialLogger));
        }
        public void NamesRegisteredInParentAppearInChildGetAll()
        {
            string[] databases = { "northwind", "adventureworks", "fabrikam" };
            UnityContainer parent = new UnityContainer();
            parent.RegisterInstance<string>("nwnd", databases[0])
                .RegisterInstance<string>("advwks", databases[1]);

            IUnityContainer child = parent.CreateChildContainer()
                .RegisterInstance<string>("fbkm", databases[2]);

            List<string> dbs = new List<string>(child.ResolveAll<string>());
            CollectionAssert.AreEquivalent(databases, dbs);
        }
        public void ChildConfigurationOverridesParentConfiguration()
        {
            UnityContainer parent = new UnityContainer();
            parent.RegisterType<ILogger, MockLogger>();
            IUnityContainer child = parent.CreateChildContainer()
                .RegisterType<ILogger, SpecialLogger>();

            ILogger parentLogger = parent.Resolve<ILogger>();
            ILogger childLogger = child.Resolve<ILogger>();

            Assert.IsInstanceOfType(parentLogger, typeof(MockLogger));
            Assert.IsInstanceOfType(childLogger, typeof(SpecialLogger));
        }
Esempio n. 36
0
        public void CanDisposeChildWithoutDisposingParent()
        {
            DisposableObject parentSpy = new DisposableObject();
            DisposableObject childSpy = new DisposableObject();

            UnityContainer parent = new UnityContainer();
            parent.RegisterInstance(parentSpy);

            IUnityContainer child = parent.CreateChildContainer()
                .RegisterInstance(childSpy);

            child.Dispose();
            Assert.False(parentSpy.WasDisposed);
            Assert.True(childSpy.WasDisposed);

            childSpy.WasDisposed = false;

            parent.Dispose();
            Assert.True(parentSpy.WasDisposed);
            Assert.False(childSpy.WasDisposed);
        }
Esempio n. 37
0
        public void DisposingParentDisposesChild()
        {
            UnityContainer parent = new UnityContainer();
            IUnityContainer child = parent.CreateChildContainer();

            DisposableObject spy = new DisposableObject();
            child.RegisterInstance<DisposableObject>(spy);

            parent.Dispose();
            Assert.True(spy.WasDisposed);
        }
Esempio n. 38
0
        public void ChildExtensionDoesntAffectParent()
        {
            bool factoryWasCalled = false;

            UnityContainer parent = new UnityContainer();
            IUnityContainer child = parent.CreateChildContainer()
                .RegisterType<object>(new InjectionFactory(c =>
                {
                    factoryWasCalled = true;
                    return new object();
                }));

            parent.Resolve<object>();
            Assert.False(factoryWasCalled);

            child.Resolve<object>();
            Assert.True(factoryWasCalled);
        }
        public void FactoryRecievesCurrentContainerWhenUsingChildWhenUsingInjectionFactory()
        {
            bool factoryWasCalled = false;
            IUnityContainer parent = new UnityContainer();

            IUnityContainer child = parent.CreateChildContainer();

            parent.RegisterType<MockDatabase>(
                new InjectionFactory(c => {
                        factoryWasCalled = true;
                        Assert.AreSame(child, c);
                        return MockDatabase.Create("connectionString");
                    }));

            child.Resolve<MockDatabase>();
            Assert.IsTrue(factoryWasCalled);
        }
        public void FactoryRecievesCurrentContainerWhenUsingChild()
        {
            IUnityContainer parent = new UnityContainer();

            IUnityContainer child = parent.CreateChildContainer();

            parent
                .AddNewExtension<StaticFactoryExtension>()
                .Configure<StaticFactoryExtension>()
                .RegisterFactory<MockDatabase>(
                c =>
                    {
                        Assert.AreSame(child, c);
                        return MockDatabase.Create("connectionString");
                    });

             var db = child.Resolve<MockDatabase>();
        }
Esempio n. 41
0
        public void ContainerRaisesChildContainerCreatedToExtension()
        {
            bool childContainerEventRaised = false;
            var mockExtension = new MockContainerExtension();

            var container = new UnityContainer()
                .AddExtension(mockExtension);

            mockExtension.Context.ChildContainerCreated += (sender, ev) =>
                {
                    childContainerEventRaised = true;
                };

            var child = container.CreateChildContainer();
            Assert.IsTrue(childContainerEventRaised);
        }
Esempio n. 42
0
        public void ChildContainerCreatedEventGivesChildContainerToExtension()
        {
            var mockExtension = new MockContainerExtension();
            ExtensionContext childContext = null;

            var container = new UnityContainer()
                .AddExtension(mockExtension);

            mockExtension.Context.ChildContainerCreated += (sender, ev) =>
            {
                childContext = ev.ChildContext;
            };

            var child = container.CreateChildContainer();
            Assert.AreSame(child, childContext.Container);
        }