Esempio n. 1
0
        public void Combined_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<DisposableClass>("transient", new DisposingTransientLifetimeManager());
            container.RegisterType<DisposableClass>("shared", new DisposingSharedLifetimeManager());

            var transient1 = container.Resolve<DisposableClass>("transient");
            var transient2 = container.Resolve<DisposableClass>("transient");
            Assert.AreNotEqual(transient1, transient2);

            var shared1 = container.Resolve<DisposableClass>("shared");
            Assert.AreNotEqual(transient1, shared1);
            Assert.AreNotEqual(transient2, shared1);

            var shared2 = container.Resolve<DisposableClass>("shared");
            Assert.AreEqual(shared1, shared2);

            container.Teardown(transient1);
            Assert.IsTrue(transient1.Disposed);

            container.Teardown(shared2);
            Assert.IsFalse(shared2.Disposed);

            container.Teardown(shared1);
            Assert.IsTrue(shared1.Disposed);
        }
Esempio n. 2
0
        private void UnityWithConfiguration()
        {
            // Create and populate a new Unity container from configuration            
            UnityConfigurationSection UnityConfigurationSectionObject = (UnityConfigurationSection)ConfigurationManager.GetSection("UnityBlockConfiguration");
            IUnityContainer UnityContainerObject = new UnityContainer();

            UnityConfigurationSectionObject.Containers["ContainerOne"].Configure(UnityContainerObject);
            Console.WriteLine("\nRetrieved the populated Unity Container.");

            // Get the logger to write a message and display the result. No name in config file.
            ILogger ILoggerInstance = UnityContainerObject.Resolve < ILogger>();            
            Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO Default UNITY!"));

            // Resolve an instance of the appropriate class registered for ILogger 
            // Using the specified mapping name in the configuration file (may be empty for the default mapping)
            ILoggerInstance = UnityContainerObject.Resolve<ILogger>("StandardLoggerMappedInConfig");
            
            // Get the logger to write a message and display the result
            Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO StandardLogger!"));
            
            // Resolve an instance of the appropriate class registered for ILogger 
            // Using the specified mapping name (may be empty for the default mapping)
            ILoggerInstance = UnityContainerObject.Resolve<ILogger>("SuperFastLoggerMappedInConfig");
            
            // Get the logger to write a message and display the result
            Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO SuperFastLogger!"));

            // Constructor Injection.
            // Resolve an instance of the concrete MyObjectWithInjectedLogger class 
            // This class contains a reference to ILogger in the constructor parameters 
            MyObjectWithInjectedLogger MyObjectWithInjectedLoggerInstance = UnityContainerObject.Resolve<MyObjectWithInjectedLogger>();
            // Get the injected logger to write a message and display the result
            Console.WriteLine("\n" + MyObjectWithInjectedLoggerInstance.GetObjectStringResult());

            // Throws error as we are trying to create instance for interface.
            //IMyInterface IMyInterfaceObject = UnityContainerObject.Resolve<IMyInterface>();

            IMyInterface IMyInterfaceObject = UnityContainerObject.Resolve<IMyInterface>();
            Console.WriteLine("\n" + IMyInterfaceObject.GetObjectStringResult());

            //If we are not sure whether a named registration exists for an object, 
            // we can use the ResolveAll method to obtain a list of registrations and mappings, and then check for the object we need in the list returned by this method. 
            // However, this will cause the container to generate all the objects for all named registrations for the specified object type, which will affect performance.
            IEnumerable<object> IEnumerableObjects = UnityContainerObject.ResolveAll(typeof(ILogger));
            int i = 0;
            foreach (ILogger foundObject in IEnumerableObjects)
            {
                // Convert the object reference to the "real" type
                ILogger theObject = foundObject as ILogger;
                i++;
                if (null != theObject)
                {
                    Console.WriteLine(theObject.WriteMessage("Reading Object " + i.ToString()));
                }
            }
            
            UnityContainerObject.Teardown(IMyInterfaceObject);

            Console.ReadLine();
        }
        public void MassDisposable_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();
            container.RegisterType<DisposableClass>(new DisposingTransientLifetimeManager());

            var sw = new Stopwatch();
            sw.Start();
            var objects = new List<DisposableClass>();
            for (int i = 0; i < 10000; i++)
            {
                objects.Add(container.Resolve<DisposableClass>());
            }

            sw.Stop();
            Context.WriteLine("Resolve: " + sw.Elapsed.ToString());

            sw.Restart();
            for (int i = 0; i < 10000; i++)
            {
                container.Teardown(objects[i]);
                Assert.IsTrue(objects[i].Disposed);
            }

            sw.Stop();
            Context.WriteLine("Teardown: " + sw.Elapsed.ToString());
        }
Esempio n. 4
0
        public void TransientParentWithSharedChild_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<ClassWithDisposable>(new DisposingTransientLifetimeManager());
            container.RegisterType<DisposableClass>(new DisposingSharedLifetimeManager());

            var obj1 = container.Resolve<ClassWithDisposable>();
            var obj2 = container.Resolve<ClassWithDisposable>();

            container.Teardown(obj1);
            Assert.IsFalse(obj2.Disposable.Disposed);

            container.Teardown(obj2);
            Assert.IsTrue(obj2.Disposable.Disposed);
        }
        public void ClassWithTwoDisposables_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<DisposableClass>(new DisposingSharedLifetimeManager());

            var obj1 = container.Resolve<ClassWithTwoDisposables>();
            Assert.AreEqual(obj1.Disposable, obj1.Disposable2);

            var obj2 = container.Resolve<ClassWithTwoDisposables>();
            Assert.AreEqual(obj1.Disposable, obj2.Disposable);
            Assert.AreEqual(obj1.Disposable, obj2.Disposable2);
            Assert.AreNotEqual(obj1, obj2);

            container.Teardown(obj1);
            Assert.IsFalse(obj1.Disposable.Disposed);

            container.Teardown(obj2);
            Assert.IsTrue(obj2.Disposable.Disposed);
        }
Esempio n. 6
0
        private void UnityAtRuntime()
        {
            // Create a new Unity container
            IUnityContainer UnityContainerObject = new UnityContainer();
            Console.WriteLine("\nRetrieved the populated Unity Container.");

            // Resolve an instance (Create an object) of the class registered for ILogger.
            // And inejcts the object which specified in config file container section.
            ILogger ILoggerObject = UnityContainerObject.Resolve<MyLogger>();

            // Invoke the method from Injected object and display the result
            Console.WriteLine("\n" + ILoggerObject.WriteMessage("My Logger"));

            UnityContainerObject.Teardown(ILoggerObject);

            
            // Register a new default (un-named) mapping with the container
            // This will replaces the existing mapping in the container for ILogger            
            UnityContainerObject.RegisterType<ILogger, MyFastLogger>();
            Console.WriteLine("\nRegistered a new mapping for IMyInterface to MyOtherObject.");

            ILoggerObject = UnityContainerObject.Resolve<ILogger>();
            Console.WriteLine("\n" + ILoggerObject.WriteMessage("Fast Logger"));

            // Resolve an instance of the appropriate class registered for ILogger 
            // Using the specified mapping name in the configuration file (may be empty for the default mapping)
            ILogger ILoggerInstance = UnityContainerObject.Resolve<ILogger>("StandardLogger");

            // Get the logger to write a message and display the result
            Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO UNITY!"));

            // Resolve an instance of the appropriate class registered for ILogger 
            // Using the specified mapping name (may be empty for the default mapping)
            ILoggerInstance = UnityContainerObject.Resolve<ILogger>("SuperFastLogger");            // This name specifies the type of logger required

            // Get the logger to write a message and display the result
            Console.WriteLine("\n" + ILoggerInstance.WriteMessage("HELLO UNITY!"));

            // Resolve an instance of the concrete MyObjectWithInjectedLogger class 
            // This class contains a reference to ILogger in the constructor parameters
            MyObjectWithInjectedLogger MyObjectWithInjectedLoggerInstance = UnityContainerObject.Resolve<MyObjectWithInjectedLogger>();
            
            // Get the injected logger to write a message and display the result
            Console.WriteLine("\n" + MyObjectWithInjectedLoggerInstance.GetObjectStringResult());

            Console.ReadLine();
        }
        public void CreateNewAfterDispose_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<DisposableClass>(new DisposingSharedLifetimeManager());

            var obj1 = container.Resolve<DisposableClass>();
            container.Teardown(obj1);
            Assert.IsTrue(obj1.Disposed, "After teardown of only instance, object should be disposed.");

            var obj2 = container.Resolve<DisposableClass>();
            Assert.AreNotEqual(obj1, obj2, "Object was previously disposed, new instance should be created.");

            var obj3 = container.Resolve<DisposableClass>();
            Assert.AreEqual(obj2, obj3, "Second reference to the same object expected.");
        }
        public void ForgottenTeardown_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            container.RegisterType<DisposableClass>(new DisposingSharedLifetimeManager());

            var obj1 = container.Resolve<ClassWithDisposable>();
            var obj2 = container.Resolve<ClassWithDisposable>();
            var obj3 = container.Resolve<ClassWithDisposable>();

            var wr = new WeakReference(obj1);
            obj1 = null;

            GC.Collect();
            Assert.IsFalse(wr.IsAlive);

            container.Teardown(obj2);
            Assert.IsFalse(obj2.Disposable.Disposed);

            container.Teardown(obj3);
            Assert.IsTrue(obj2.Disposable.Disposed);
        }
Esempio n. 9
0
        public void TeardownParsleyAsCachedDisposesParsleyWhenCacheLifetimeStrategyExtensionIsAdded()
        {
            var container = new UnityContainer();
            container.AddNewExtension<CacheLifetimeStrategyExtension>();

            var lease = new SlidingLease(TimeSpan.FromTicks(1));
            var cache = new CacheLifetimeManager(lease);
            container.RegisterType<IIngredient, Parsley>(cache);

            var ingredient = container.Resolve<IIngredient>();

            Thread.Sleep(TimeSpan.FromMilliseconds(1));

            container.Teardown(ingredient);

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.True(parsley.IsDisposed);
        }
        public void RegisteredAsDisposable_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();
            container.RegisterType<DisposableClass>(new DisposingTransientLifetimeManager());

            var obj1 = container.Resolve<DisposableClass>();
            var obj2 = container.Resolve<DisposableClass>();
            Assert.AreNotEqual(obj1, obj2);

            container.Teardown(obj1);
            Assert.IsTrue(obj1.Disposed);

            container.Teardown(obj2);
            Assert.IsTrue(obj2.Disposed);
        }
Esempio n. 11
0
        public void TeardownParsleyAsPerResolveDoesNotDisposeParsley()
        {
            var container = new UnityContainer();
            container.RegisterType<IIngredient, Parsley>(new PerResolveLifetimeManager());

            var ingredient = container.Resolve<IIngredient>();

            container.Teardown(ingredient);

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.False(parsley.IsDisposed); // <-- Boo hiss!!
        }
Esempio n. 12
0
        public void TeardownParsleyAsSingletonDoesNotDisposeParsley()
        {
            var container = new UnityContainer();
            container.RegisterType<IIngredient, Parsley>(new ContainerControlledLifetimeManager());

            var ingredient = container.Resolve<IIngredient>();

            container.Teardown(ingredient);

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.False(parsley.IsDisposed);
        }
        public void MixedRegistrations_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();
            container.RegisterType<DisposableClass>(new DisposingTransientLifetimeManager());
            container.RegisterType<DisposableClass>("transient");

            var disposingObj = container.Resolve<DisposableClass>();
            var disposingObj2 = container.Resolve<DisposableClass>("disposing");
            var transientObj = container.Resolve<DisposableClass>("transient");

            Assert.AreNotEqual(disposingObj, disposingObj2);
            Assert.AreNotEqual(disposingObj, transientObj);

            container.Teardown(disposingObj);
            Assert.IsTrue(disposingObj.Disposed);

            container.Teardown(disposingObj2);
            Assert.IsTrue(disposingObj.Disposed);

            container.Teardown(transientObj);
            Assert.IsFalse(transientObj.Disposed);
        }
        public void UnregisteredGenericParent_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            var obj1 = container.Resolve<GenericClass<SimpleClass>>();
            var obj2 = container.Resolve<GenericClass<DisposableClass>>();
            Assert.AreNotEqual(obj1, obj2);

            container.Teardown(obj1);
            container.Teardown(obj2);
            Assert.IsFalse(obj2.Property.Disposed);
        }
        public void UnregisteredClass_Test()
        {
            var container = new UnityContainer();
            container.AddNewExtension<DisposableStrategyExtension>();

            var obj1 = container.Resolve<DisposableClass>();
            var obj2 = container.Resolve<DisposableClass>();
            Assert.AreNotEqual(obj1, obj2);

            container.Teardown(obj1);
            Assert.IsFalse(obj1.Disposed);

            container.Teardown(obj2);
            Assert.IsFalse(obj2.Disposed);
        }
Esempio n. 16
0
        public void TeardownParsleyAsCachedDoesNotDisposeParsley()
        {
            var container = new UnityContainer();
            container.RegisterType<IIngredient, Parsley>(new CacheLifetimeManager(new SlidingLease(TimeSpan.FromMinutes(1))));

            var ingredient = container.Resolve<IIngredient>();

            container.Teardown(ingredient);

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.False(parsley.IsDisposed); // <-- Boo hiss!!
        }
        public void NonDisposable_Test()
        {
            using (var container = new UnityContainer())
            {
                container.AddNewExtension<DisposableStrategyExtension>();
                container.RegisterType<SimpleClass>(new DisposingTransientLifetimeManager());

                var obj1 = container.Resolve<SimpleClass>();
                container.Teardown(obj1);
            }
        }