Ejemplo n.º 1
0
        public void ResolveAllOnlyReturnsInterfaceRegistrations()
        {
            ITest iTest;

            ATest objA = new ATest();
            BTest objB = new BTest();
            CTest objC = new CTest();

            objA.Strtest = "Hi";

            UnityContainer uc1 = new UnityContainer();

            uc1.RegisterType<ITest, ATest>();

            iTest = objA;
            uc1.RegisterInstance("ATest", iTest);
            iTest = objB;
            uc1.RegisterInstance("BTest", iTest);
            iTest = objC;
            uc1.RegisterInstance("CTest", iTest);

            List<ATest> list = new List<ATest>(uc1.ResolveAll<ATest>());
            List<ITest> list3 = new List<ITest>(uc1.ResolveAll<ITest>());

            Assert.AreEqual(0, list.Count);
            Assert.AreEqual(3, list3.Count);
        }
        public void Can_add_all_as_singletons()
        {
            var container = new UnityContainer();

            container.Configure(x => x.Scan(scan =>
            {
                scan.AssemblyContaining<FooRegistry>();
                scan.WithAddAllConvention().TypesImplementing<IHaveManyImplementations>().AsSingleton();
            }));

            Assert.That(container.ResolveAll<IHaveManyImplementations>().First(), Is.SameAs(container.ResolveAll<IHaveManyImplementations>().First()));
        }
        public void Adds_all_types_implementing_the_specified_type_with_default_name()
        {
            var container = new UnityContainer();

            container.Configure(x => x.Scan(scan =>
            {
                scan.AssemblyContaining<FooRegistry>();
                scan.WithAddAllConvention().TypesImplementing<IHaveManyImplementations>();
            }));

            Assert.That(container.ResolveAll<IHaveManyImplementations>().Count(), Is.EqualTo(2));
            Assert.That(container.ResolveAll<IHaveManyImplementations>().First(), Is.Not.SameAs(container.ResolveAll<IHaveManyImplementations>().First()));
        }
Ejemplo n.º 4
0
        public void RegisterSameType()
        {
            IUnityContainer uc = new UnityContainer()
                .RegisterType<ITemporary, Temp>("First");

            List<ITemporary> temporaries = new List<ITemporary>(uc.ResolveAll<ITemporary>());

            Assert.AreEqual(1, temporaries.Count);

            uc.RegisterType<ITemporary, Temp2>("First");
            temporaries = new List<ITemporary>(uc.ResolveAll<ITemporary>());

            Assert.AreEqual(1, temporaries.Count);
        }
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();

            // only do this if CSLA DataPortal is NOT deployed on a physical server
            // if this Appsetting has value, it means that DataPortal is on a separate physical server
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["CslaDataPortalProxy"]))
            {
                // register all the composers you need to properly register dependencies that are used in your business objects
                // add a name to properly distinguish each belonging to type IContainerComposer
                // so that ResolveAll<IContainerComposer>() will actually return a value
                container.RegisterType(typeof(IContainerComposer), typeof(DataContextComposer), typeof(DataContextComposer).ToString());
                container.RegisterType(typeof(IContainerComposer), typeof(JustAnotherSampleServiceComposer), typeof(JustAnotherSampleServiceComposer).ToString());

                ApplicationContext.DataPortalActivator = new CustomDataPortalActivator(container.ResolveAll<IContainerComposer>());
                CS.DataPortal.InterceptorType = typeof(CustomDataPortalInterceptor);
            }

            // call your bootstrapper for your UI dependencies
            bootstrapUIDependencies(container);


            MyExecutionClass runner = container.Resolve<MyExecutionClass>();
            runner.Run();
        }
Ejemplo n.º 6
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();
        }
Ejemplo n.º 7
0
        public static IUnityContainer CreateUnityContainer()
        {
            var container = new UnityContainer();
            container.RegisterType<IMediator, Mediator>();
            var types = AllClasses.FromAssemblies( typeof( Program ).Assembly );

            container.RegisterTypes(
                types,
                WithMappings.FromAllInterfaces,
                GetName,
                GetLifetimeManager,
                null,
                true );

            container.RegisterInstance<SingleInstanceFactory>( t =>
             {
                 var pipeline = container.Resolve(
                     typeof( MediatorPipeline<,> ).MakeGenericType( t.GetGenericArguments() )
                 );

                 return pipeline;

             } );
            container.RegisterInstance<MultiInstanceFactory>( t => container.ResolveAll( t ) );

            return container;
        }
Ejemplo n.º 8
0
        public void FixtureSetup()
        {
            this.unityContainer = new UnityContainer();
            IoC.Initialize(
                (x, y) => this.unityContainer.RegisterType(x, y),
                (x, y) => this.unityContainer.RegisterInstance(x, y),
                (x) => { return unityContainer.Resolve(x); },
                (x) => { return unityContainer.ResolveAll(x); });

            // Context Factory
            RavenUnitOfWorkFactory ctxFactory = new RavenUnitOfWorkFactory();
            Raven.Client.Document.DocumentStore sessionFactory = ctxFactory.CreateDocumentStore();

            IoC.RegisterInstance<IDatabaseManager>(ctxFactory);
            IoC.RegisterInstance<IUnitOfWorkFactory>(ctxFactory);

            this.unityContainer.RegisterType<IDocumentSession, IDocumentSession>(new InjectionFactory((c) =>
            {
                return ctxFactory.CurrentDocumentSession;
            }));

            // Repositories
            this.unityContainer.RegisterType<IEntityARepository, EntityARavenRepository>();

            // Services
            if (!ctxFactory.DatabaseExists())
            {
                ctxFactory.CreateDatabase();
            }

            ctxFactory.ValidateDatabaseSchema();
        }
Ejemplo n.º 9
0
        public void RegisterTypeWithoutNameandGetAll()
        {
            IUnityContainer uc = new UnityContainer().RegisterType<ITemporary, Temp>().RegisterType<ITemporary, Temporary>();

            List<ITemporary> temporaries = new List<ITemporary>(uc.ResolveAll<ITemporary>());

            Assert.AreEqual(0, temporaries.Count);
        }
Ejemplo n.º 10
0
 public void ConfigureContainerbyAddingExteralPolicy()
 {
     IUnityContainer container = new UnityContainer();
     container.AddNewExtension<Interception>();
     container.Configure<Interception>().AddPolicy("myRDP");
     List<InjectionPolicy> policy = new List<InjectionPolicy>(container.ResolveAll<InjectionPolicy>());
     Assert.AreEqual("myRDP", policy[1].Name);
 }
Ejemplo n.º 11
0
        public void ResolvingAllRegistratiosnForaTypeReturnsAnEmptyArrayWhenNothingIsRegisterd()
        {
            IUnityContainer container = new UnityContainer();

            IEnumerable<CollectionSupportTestClass> resolved = container.ResolveAll<CollectionSupportTestClass>();
            List<CollectionSupportTestClass> resolvedList = new List<CollectionSupportTestClass>(resolved);

            Assert.AreEqual(0, resolvedList.Count);
        }
Ejemplo n.º 12
0
 public void ConfigureContainerbyAddingEmptyHandlerRuleThrowException()
 {
     IUnityContainer container = new UnityContainer();
     container.AddNewExtension<Interception>();
     container.Configure<Interception>().
         AddPolicy("myRDP").
         AddCallHandler(String.Empty).
         AddMatchingRule(String.Empty);
     List<InjectionPolicy> policy = new List<InjectionPolicy>(container.ResolveAll<InjectionPolicy>());
 }
Ejemplo n.º 13
0
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();

            container.RegisterType<IMovieDataAccess, YoutubeService>("YoutubeService");
            container.RegisterType<IMovieDataAccess, OMDBService>("OMDBService");
            container.RegisterInstance<IAppCache>(MovieTrailers.DataAccess.AppCache.Instance);
            container.RegisterInstance<IMovieTrailerService>(new MovieTrailerService(container.ResolveAll<IMovieDataAccess>()));
            return container;
        }
Ejemplo n.º 14
0
        public void RegisterMultipleImplementationsOfTheSameType()
        {
            var container = new UnityContainer();
            container.RegisterType<IIngredient, Steak>("meat");
            container.RegisterType<IIngredient, SauceBéarnaise>("sauce");

            var ingredients = container.ResolveAll<IIngredient>();

            Assert.True(ingredients.OfType<Steak>().Any());
            Assert.True(ingredients.OfType<SauceBéarnaise>().Any());
        }
        public void Can_add_all_implementations_of_an_open_generic()
        {
            var container = new UnityContainer();

            container.Configure(x => x.Scan(scan =>
            {
                scan.AssemblyContaining<FooRegistry>();
                scan.WithAddAllConvention().TypesImplementing(typeof(IHandler<>));
            }));

            Assert.That(container.ResolveAll<IHandler<Message>>().Count(), Is.EqualTo(2));
        }
Ejemplo n.º 16
0
        public void ResolvingAllRegistratiosnForaTypeReturnsAnEquivalentArrayWhenItemsAreRegisterd()
        {
            IUnityContainer container = new UnityContainer();
            container.RegisterType<CollectionSupportTestClass>("Element1", new ContainerControlledLifetimeManager());
            container.RegisterType<CollectionSupportTestClass>("Element2", new ContainerControlledLifetimeManager());
            container.RegisterType<CollectionSupportTestClass>("Element3", new ContainerControlledLifetimeManager());

            IEnumerable<CollectionSupportTestClass> resolved = container.ResolveAll<CollectionSupportTestClass>();
            List<CollectionSupportTestClass> resolvedList = new List<CollectionSupportTestClass>(resolved);

            Assert.AreEqual(3, resolvedList.Count);
        }
Ejemplo n.º 17
0
        public void ResolveMultipleInstances() {

            var container = new UnityContainer();


            container.RegisterType<IFruit,Apple>("a");
            container.RegisterType<IFruit, Pear>("b");

            var ss = container.ResolveAll<IFruit>();

            Assert.AreEqual(2,ss.Count());
        }
Ejemplo n.º 18
0
        internal static IUnityContainer BuildMediator()
        {
            var container = new UnityContainer();
            container.RegisterType<IMediator, Mediator>();
            container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly), WithMappings.FromAllInterfaces, GetName, GetLifetimeManager);
            container.RegisterType(typeof(INotificationHandler<>), typeof(GenericHandler), GetName(typeof(GenericHandler)));
            container.RegisterType(typeof(IAsyncNotificationHandler<>), typeof(GenericAsyncHandler), GetName(typeof(GenericAsyncHandler)));
            container.RegisterInstance(Console.Out);
            container.RegisterInstance<SingleInstanceFactory>(t => container.Resolve(t));
            container.RegisterInstance<MultiInstanceFactory>(t => container.ResolveAll(t));

            return container;
        }
Ejemplo n.º 19
0
        public void CanGetAllValidators()
        {
            UnityContainer container = new UnityContainer();
            container.ConfigureAutoRegistration().
                Include(t => InTargetAssembly(t),
                Then.Register().AsAllInterfacesOfType()).
                Include(If.Implements<IValidator>, Then.Register().As<IValidator>().WithTypeName()).
                ApplyAutoRegistration();

            var validators = container.ResolveAll<IValidator>();

            Assert.IsNotNull(validators);
            Assert.AreEqual(3, validators.Count());
        }
Ejemplo n.º 20
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var container = new UnityContainer();

            System.Web.Mvc.DependencyResolver.SetResolver((t) => container.Resolve(t), (t) => container.ResolveAll(t));

            var cache = CacheFactory.FromConfiguration<int>("myCache");
            container.RegisterInstance(cache);
        }
Ejemplo n.º 21
0
        public void RegisterTypeAndCheckOrder()
        {
            IUnityContainer uc = new UnityContainer()
                .RegisterType<ITemporary, Temp>("First")
                .RegisterType<ITemporary, Temp>()
                .RegisterType<ITemporary, Temporary>("Second");
            List<ITemporary> temporaries = new List<ITemporary>(uc.ResolveAll<ITemporary>());

            Assert.AreEqual(2, temporaries.Count);

            bool caseOne = (temporaries[0] is Temp) && (temporaries[1] is Temporary);
            bool caseTwo = (temporaries[0] is Temporary) && (temporaries[1] is Temp);

            Assert.IsTrue(caseOne || caseTwo);
        }
Ejemplo n.º 22
0
        public void CanFilterOutValidatorRegistrations()
        {
            UnityContainer container = new UnityContainer();
            container.ConfigureAutoRegistration().
                Include(t => InTargetAssembly(t),
                Then.Register().AsAllInterfacesOfType()).
                Exclude(If.Is<FailValidator>).
                Include(If.Implements<IValidator>, Then.Register().As<IValidator>().WithTypeName()).
                ApplyAutoRegistration();

            // excluding the FailValidator should leave 2 of them
            var validators = container.ResolveAll<IValidator>();

            Assert.IsNotNull(validators);
            Assert.AreEqual(2, validators.Count());
        }
Ejemplo n.º 23
0
        static void ResolveAllDemo()
        {
            Console.WriteLine("\n<<< ResolveAllDemo >>>");

            var container = new UnityContainer();
            container.RegisterType<IMessageService, EmailService>();  // 預設註冊
            container.RegisterType<IMessageService, EmailService>("Email"); // 具名註冊
            container.RegisterType<IMessageService, SmsService>("SMS");   // 具名註冊
            container.RegisterType<IMessageService, SmsService>("SMS");   // 具名註冊

            // 解析物件
            var services = container.ResolveAll<IMessageService>();
            foreach (var svc in services)
            {
                svc.SendMessage("Michael", "You are resolved.");
            }
        }
Ejemplo n.º 24
0
        private static void CodeIoc()
        {
            IUnityContainer container = new UnityContainer();

            container.RegisterType<IClass, CbClass>();

            container.RegisterType<IClass, EcClass>("ec");

            IClass ecClass = container.Resolve<IClass>("ec");
            ecClass.ShowInfo();

            IClass dcClass = container.Resolve<IClass>();
            dcClass.ShowInfo();

            IEnumerable<IClass> classList = container.ResolveAll<IClass>();
            foreach (var item in classList) {
                item.ShowInfo();
            }

            Console.ReadKey();
        }
Ejemplo n.º 25
0
		public static UnityContainer Initialize(string path, TerrificNetHostConfiguration configuration, ServerConfiguration serverConfiguration)
		{
			var container = new UnityContainer();
		    container.RegisterType<ITerrificTemplateHandler, DefaultTerrificTemplateHandler>();
			container 
				.RegisterType
				//<ITerrificTemplateHandlerFactory, GenericUnityTerrificTemplateHandlerFactory<DefaultTerrificTemplateHandler>>();
				<ITerrificTemplateHandlerFactory, GenericUnityTerrificTemplateHandlerFactory<PageEditDefaultTerrificTemplateHandler>>();
			container.RegisterType<INamingRule, NamingRule>();
			container.RegisterInstance(serverConfiguration);

			new DefaultUnityModule().Configure(container);

#if DEBUG
		    var fileSystem = new FileSystem(path);
		    container.RegisterInstance<IFileSystem>(fileSystem);
#else
			container.RegisterInstance<IFileSystem>(new EmbeddedResourceFileSystem(typeof(WebInitializer).Assembly));
#endif

            foreach (var item in configuration.Applications.Values)
			{
				var childContainer = container.CreateChildContainer();

				var app = DefaultUnityModule.RegisterForApplication(childContainer, path, item.BasePath,
					item.ApplicationName, item.Section);
				container.RegisterInstance(item.ApplicationName, app);
			}

			foreach (var app in container.ResolveAll<TerrificNetApplication>())
			{
				foreach (var template in app.Container.Resolve<ITemplateRepository>().GetAll())
				{
					Console.WriteLine(template.Id);
				}
			}

			new TerrificBundleUnityModule().Configure(container);
			return container;
		}
Ejemplo n.º 26
0
 static void Main(string[] args)
 {
     var container = new UnityContainer();
     var reqInterfaces = new[] { typeof(IGetInfo) };
     var assemblies = Directory.GetFiles(@"C:\oop\", "*.dll");
     var maps = from assembly in assemblies
                from type in Assembly.LoadFile(assembly).GetTypes()
                from reqInterface in reqInterfaces
                where reqInterface.IsAssignableFrom(type)
                select new MyType
                {
                    Interface = reqInterface,
                    Type = type,
                    Name = type.Name
                };
     Bootstrapper.Setup(container, maps);
     var list = container.ResolveAll<IGetInfo>();
     foreach (var l in list)
     {
         l.GetInfo();
     }
 }
Ejemplo n.º 27
0
        public static void RegisterComponents(HttpConfiguration config)
        {
            UnityContainer container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<ITestService, TestService>();

            container.RegisterType<ILogEntryProcessor, ErrorLogCacheHandler>("ErrorHandler", new ContainerControlledLifetimeManager());
            container.RegisterType<ILogEntryProcessor, LogEntryHandler>("DefaultHandler", new ContainerControlledLifetimeManager());
            container.RegisterType<IObservable<AppLogEntry>, Subject<AppLogEntry>>(new ContainerControlledLifetimeManager());
            container.RegisterType<IObserver<AppLogEntry>, Subject<AppLogEntry>>(new ContainerControlledLifetimeManager());
            //container.RegisterInstance(GlobalConfiguration.Configuration);
            
            //GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            config.DependencyResolver = new UnityDependencyResolver(container);

            //Start a new heimdall engine.
            //container.ResolveAll<IHeimdallEngine>();
            container.ResolveAll<ILogEntryProcessor>();            

        }
Ejemplo n.º 28
0
        private static void ConfigIoc()
        {
            IUnityContainer container = new UnityContainer();

            var section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
            container.LoadConfiguration(section, "FirstClass");

            //解析默认对象
            IClass cbClass = container.Resolve<IClass>();
            cbClass.ShowInfo();

            //指定命名解析对象
            IClass ecClass = container.Resolve<IClass>("ec");
            ecClass.ShowInfo();

            //获取容器中所有IClass的注册的已命名对象
            IEnumerable<IClass> classList = container.ResolveAll<IClass>();
            foreach (var item in classList) {
                item.ShowInfo();
            }

            Console.ReadKey();
        }
Ejemplo n.º 29
0
        protected void regedit()
        {
            Log4NetManager.Initialize("log4net.config");
            LoggerManager.Logger.Info("应用程序启动");

            this.unityContainer = new UnityContainer();
            IoC.Initialize(
                (x, y) => this.unityContainer.RegisterType(x, y),
                (x, y) => this.unityContainer.RegisterInstance(x, y),
                (x) => { return unityContainer.Resolve(x); },
                (x) => { return unityContainer.ResolveAll(x); });

            // Context Factory
            EFUnitOfWorkFactory ctxFactory = new EFUnitOfWorkFactory(this.ConnectionString(), typeof(DomainContext));

            if (!ctxFactory.DatabaseExists())
            {
                ctxFactory.CreateDatabase();
            }

            ctxFactory.ValidateDatabaseSchema();

            this.unityContainer.RegisterInstance<IDatabaseManager>(ctxFactory);
            this.unityContainer.RegisterInstance<IUnitOfWorkFactory>(ctxFactory);

            this.unityContainer.RegisterType<DbContext, DomainContext>(new InjectionFactory((c) =>
            {
                return ctxFactory.CurrentDbContext;
            }));

            // Repositories
            //this.unityContainer.RegisterType<categoryRepository, categoryRepository>(new PerResolveLifetimeManager());

            UnityControllerFactory factory = new UnityControllerFactory(unityContainer);
            ControllerBuilder.Current.SetControllerFactory(factory);
        }
        public void CanOverrideInjectionPropertyForPolymorphicTypesInCollection()
        {
            TypeToInjectForPropertyOverride1 defaultInjected = new TypeToInjectForPropertyOverride1(111);
            TypeToInjectForPropertyOverride2 overrideInjected = new TypeToInjectForPropertyOverride2(222);

            UnityContainer container = new UnityContainer();

            container.RegisterType<ISubjectTypeToInjectForPropertyOverride, SubjectType1ToInjectForPropertyOverride>(
                "Test1", new InjectionProperty("InjectedObject", defaultInjected));
            container.RegisterType<ISubjectTypeToInjectForPropertyOverride, SubjectType2ToInjectForPropertyOverride>(
                "Test2", new InjectionProperty("InjectedObject", defaultInjected));
            container.RegisterType<ISubjectTypeToInjectForPropertyOverride, SubjectType3ToInjectForPropertyOverride>(
                "Test3", new InjectionProperty("InjectedObject", defaultInjected));

            var resultList =
                container.ResolveAll<ISubjectTypeToInjectForPropertyOverride>(new PropertyOverride("InjectedObject",
                    overrideInjected));

            int count = 0;
            foreach (var result in resultList)
            {
                count++;
                Assert.IsInstanceOfType(result.InjectedObject, typeof(TypeToInjectForPropertyOverride2));
            }

            Assert.AreEqual<int>(3, count);
        }