Exemplo n.º 1
0
        private static IUnityContainer BuildUnityContainer()
        {
            UnityContainer tempContainer = null;
            UnityContainer container;

            try
            {
                tempContainer = new UnityContainer();

                // Register your container mappings in the config file.
                // It will get loaded into the container with the following call:
                tempContainer.LoadConfiguration();

                container = tempContainer;
                tempContainer = null;
            }
            finally
            {
                if (tempContainer != null)
                {
                    tempContainer.Dispose();
                }
            }

            return container;
        }
Exemplo n.º 2
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

               UnityContainer container = new UnityContainer();
               var mainView = container.Resolve<MainWindow>();
               container.Dispose();
               mainView.Show();
        }
Exemplo n.º 3
0
        public void DisposingParentDisposesChild()
        {
            UnityContainer parent = new UnityContainer();
            IUnityContainer child = parent.CreateChildContainer();

            MyDisposableObject spy = new MyDisposableObject();
            child.RegisterInstance(spy);
            parent.Dispose();

            Assert.IsTrue(spy.WasDisposed);
        }
        public void MefDisposesMefComponentTest()
        {
            // Setup
            var unityContainer = new UnityContainer();
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            // Register catalog and types
            unityContainer.RegisterCatalog(assemblyCatalog);
            unityContainer.RegisterType<IUnityOnlyComponent, UnityOnlyComponent1>();

            // Test
            var container = unityContainer.Resolve<CompositionContainer>();
            var mefComponentDisposable = container.GetExportedValue<MefComponentDisposable>();
            Assert.That(mefComponentDisposable, Is.Not.Null);
            Assert.That(mefComponentDisposable.GetType(), Is.EqualTo(typeof(MefComponentDisposable)));

            unityContainer.Dispose();

            Assert.IsTrue(mefComponentDisposable.Disposed);
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();
            try
            {
                container.RegisterType<IUnitOfWork, UnitOfWork>();
                container.RegisterType<IWidgetController, WidgetController>();

                /* Registering ViewModels */

                //Standard ViewModels
                container.RegisterType<IWidgetContainerViewModel, WidgetContainerViewModel>();

                //Control ViewModels
                container.RegisterType<IImageWidgetViewModel, ImageWidgetViewModel>();
                container.RegisterType<ITextWidgetViewModel, TextWidgetViewModel>();

                /* Mapping Model to ViewModel */

                container.RegisterFactory<IWidgetContainer, IWidgetContainerViewModel>().AddDefaultMap();

                container.RegisterFactory<IWidget, IWidgetViewModel>()
                    .AddMap<IImageWidget, IImageWidgetViewModel>()
                    .AddMap<ITextWidget, ITextWidgetViewModel>();

                /* Run Program */

                var controller = container.Resolve<IWidgetController>();
                controller.ShowWidgits(1);

                /* End Program */

                Console.WriteLine();
                Console.WriteLine("Please press any key to continue. . .");
                Console.ReadKey(true);
            }
            finally
            {
                container.Dispose();
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Method bootstraps application and runs the application
        /// </summary>
        /// <param name="args">Command line arguements passed in</param>
        static void Main(string[] args)
        {
            AutoMapperExtensions.Build();

            var container = new UnityContainer();

            container.RegisterType<IOutputWriter, ConsoleOutputWriter>();

            if (args.Length == 2)
            {

                //Conditional Bootstrapping of the services
                container.RegisterType<IRateDatasSource, TaxRateDb>(new InjectionConstructor(new List<TaxBracket>()));
                container.RegisterType<ISalarySlipService, MonthlySalarySlipService>();
                container.RegisterType<IFileProcessor, SalaryDataFileProcessor>("SalaryProcessor");
                container.RegisterType<IFileProcessor, RatesDataFileProcessor>("RatesProcessor");
                container.RegisterType<ITaxService, TaxCalculationService>();

                //Load tax rates from file
                container.Resolve<IFileProcessor>("RatesProcessor").Run(args[0]);

                //Read and Process salary from file
                container.Resolve<IFileProcessor>("SalaryProcessor").Run(args[1]);

            }
            else
            {
                //printing output writer
                container.Resolve<IOutputWriter>().WriteLine("Application Error - Please provide two paths to a rates and paypacket csv respectively");
            }

            //Console readkey
            System.Console.ReadKey();

            //Dispose Unity Container
            container.Dispose();
        }
        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();
        }
Exemplo n.º 8
0
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.

            // Web API routes
            config.MapHttpAttributeRoutes();

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            config.Filters.Add(new ExceptionHandlingAttribute());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var container = new UnityContainer();

            try
            {
                // repositories used by the application

                container.RegisterType<ConferenceRegistrationDbContext>(new TransientLifetimeManager(), new InjectionConstructor("ConferenceRegistration"));
                container.RegisterType<PaymentsReadDbContext>(new TransientLifetimeManager(), new InjectionConstructor("Payments"));

                var cache = new MemoryCache("ReadModel");
                container.RegisterType<IOrderDao, OrderDao>();
                container.RegisterType<IConferenceDao, CachingConferenceDao>(
                    new ContainerControlledLifetimeManager(),
                    new InjectionConstructor(new ResolvedParameter<ConferenceDao>(), cache));
                container.RegisterType<IPaymentDao, PaymentDao>();

                // configuration specific settings

                var serializer = new JsonTextSerializer();
                container.RegisterInstance<ITextSerializer>(serializer);

                container.RegisterType<IBlobStorage, SqlBlobStorage>(new ContainerControlledLifetimeManager(), new InjectionConstructor("BlobStorage"));
                container.RegisterType<Infrastructure.Sql.Messaging.IMessageSender, MessageSender>(
                    "Commands", new TransientLifetimeManager(), new InjectionConstructor(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Commands"));
                container.RegisterType<ICommandBus, Infrastructure.Sql.Messaging.CommandBus>(
                    new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<Infrastructure.Sql.Messaging.IMessageSender>("Commands"), serializer));


                config.DependencyResolver = new UnityResolver(container);

                IEventBus eventBus = null;
//#if LOCAL
            eventBus = new Infrastructure.Sql.Messaging.EventBus(new MessageSender(Database.DefaultConnectionFactory, "SqlBus", "SqlBus.Events"), serializer);
//#else
//                var settings = InfrastructureSettings.Read(HttpContext.Current.Server.MapPath(@"~\bin\Settings.xml")).ServiceBus;

//                if (!MaintenanceMode.IsInMaintainanceMode)
//                {
//                    new ServiceBusConfig(settings).Initialize();
//                }

//                eventBus = new Infrastructure.Azure.Messaging.EventBus(new TopicSender(settings, "conference/events"), new StandardMetadataProvider(), serializer);
//#endif

                container.RegisterInstance<IEventBus>(eventBus);

                var conferenceService = new ConferenceService(eventBus);

                container.RegisterInstance<ConferenceService>(conferenceService);
            }
            catch
            {
                container.Dispose();
                throw;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates an instance of <see cref="Microsoft.Practices.Unity.UnityContainer"/> from configuration using the provided container name.
        /// </summary>
        /// <param name="containerName">Container name to configure.  If containerName is null or empty, the default container is configured.</param>
        /// <returns>Created and configured <see cref="Microsoft.Practices.Unity.UnityContainer"/>.</returns>
        private static IUnityContainer CreateUnityContainer(string containerName)
        {
            IUnityContainer unityContainer = new UnityContainer();
            try
            {
                UnityConfigurationSection section = ConfigurationManager.GetSection(
                    UnityInstanceProvider.UnityConfigurationSectionName) as UnityConfigurationSection;
                if (section != null)
                {
                    if (string.IsNullOrEmpty(containerName))
                    {
                        section.Configure(unityContainer);
                    }
                    else
                    {
                        section.Configure(unityContainer, containerName);
                    }
                }
            }
            catch (Exception)
            {
                unityContainer.Dispose();
                throw;
            }

            return unityContainer;
        }
        public void DisposingUnityDisposesCompositionContainerTest()
        {
            // Setup
            var unityContainer = new UnityContainer();
            var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());

            // Add composition support for unity
            unityContainer.AddNewExtension<CompositionIntegration>();
            unityContainer.Configure<CompositionIntegration>().Catalogs.Add(assemblyCatalog);

            var compositionContainer = unityContainer.Resolve<CompositionContainer>();
            unityContainer.Dispose();
            
            Assert.That(delegate
            {
                compositionContainer.GetExport<IMefComponent>();
            }, Throws.TypeOf<ObjectDisposedException>());
        }
Exemplo n.º 11
0
        private static UnityContainer CreateContainer()
        {
            var container = new UnityContainer();
            try
            {
                // repositories used by the application

                container.RegisterType<ConferenceRegistrationDbContext>(new TransientLifetimeManager(), new InjectionConstructor("ConferenceRegistration"));
                container.RegisterType<PaymentsReadDbContext>(new TransientLifetimeManager(), new InjectionConstructor("Payments"));

                var cache = new MemoryCache("ReadModel");
                container.RegisterType<IOrderDao, OrderDao>();
                container.RegisterType<IConferenceDao, CachingConferenceDao>(
                    new ContainerControlledLifetimeManager(),
                    new InjectionConstructor(new ResolvedParameter<ConferenceDao>(), cache));
                container.RegisterType<IPaymentDao, PaymentDao>();

                // configuration specific settings

                OnCreateContainer(container);

                return container;
            }
            catch
            {
                container.Dispose();
                throw;
            }
        }
        public void WhenDisposingParentChildDisposes()
        {
            UnityContainer parent = new UnityContainer();
            IUnityContainer child = parent.CreateChildContainer();

            TestContainer3 obj = new TestContainer3();
            child.RegisterInstance<TestContainer3>(obj);

            parent.Dispose();
            Assert.IsTrue(obj.WasDisposed);
        }
Exemplo n.º 13
0
        public void DisposeContainerDisposesCachedParsley()
        {
            var container = new UnityContainer();

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

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

            container.Dispose();

            var parsley = Assert.IsAssignableFrom<Parsley>(ingredient);
            Assert.True(parsley.IsDisposed);
        }
Exemplo n.º 14
0
        public void CanDisposeChildWithoutDisposingParent()
        {
            MyDisposableObject parentSpy = new MyDisposableObject();
            MyDisposableObject childSpy = new MyDisposableObject();
            UnityContainer parent = new UnityContainer();

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

            Assert.IsFalse(parentSpy.WasDisposed);
            Assert.IsTrue(childSpy.WasDisposed);

            childSpy.WasDisposed = false;
            parent.Dispose();

            Assert.IsTrue(parentSpy.WasDisposed);
            Assert.IsFalse(childSpy.WasDisposed);
        }
Exemplo n.º 15
0
        public void GetObjectAfterDispose()
        {
            UnityContainer parent = new UnityContainer();
            parent.RegisterType<Temp>("First", new ContainerControlledLifetimeManager());

            IUnityContainer child = parent.CreateChildContainer();
            child.RegisterType<ITemporary>("First", new ContainerControlledLifetimeManager());
            parent.Dispose();
            AssertHelper.ThrowsException<ResolutionFailedException>(() => child.Resolve<ITemporary>("First"));
        }
Exemplo n.º 16
0
 public void Cleanup()
 {
     IoCContainer.Dispose();
 }