コード例 #1
0
		public void RequestSingleInterfaceProxyWithoutServiceInterface()
		{
			IWindsorContainer container = new WindsorContainer();

			container.AddComponent("standard.interceptor", typeof(StandardInterceptor));
			container.AddComponent("useSingle", typeof(CalculatorServiceWithSingleProxyBehavior));
		}
コード例 #2
0
        public void TestBasicOperationsWithInterfaceService()
        {
            WindsorContainer container = new WindsorContainer(new DefaultConfigurationStore());

            container.AddFacility("transactionmanagement", new TransactionFacility());

            container.AddComponent("transactionmanager",
                                   typeof(ITransactionManager), typeof(MockTransactionManager));

            container.AddComponent("services.customer", typeof(ICustomerService), typeof(AnotherCustomerService));

            ICustomerService service = (ICustomerService)container["services.customer"];

            service.Insert("TestCustomer", "Rua P Leite, 33");

            MockTransactionManager transactionManager = (MockTransactionManager)
                                                        container["transactionmanager"];

            Assert.AreEqual(1, transactionManager.TransactionCount);
            Assert.AreEqual(1, transactionManager.CommittedCount);
            Assert.AreEqual(0, transactionManager.RolledBackCount);

            try
            {
                service.Delete(1);
            }
            catch (Exception)
            {
                // Expected
            }

            Assert.AreEqual(2, transactionManager.TransactionCount);
            Assert.AreEqual(1, transactionManager.CommittedCount);
            Assert.AreEqual(1, transactionManager.RolledBackCount);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: rajwilkhu/MassTransit
		private static void Main(string[] args)
		{
			XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.xml"));

			var cfg = RunnerConfigurator.New(c =>
				{
					c.SetServiceName("PostalService");
					c.SetDisplayName("Sample Email Service");
					c.SetDescription("we goin' postal");

					c.RunAsLocalSystem();
					c.DependencyOnMsmq();

					c.BeforeStartingServices(a =>
						{
							var container = new WindsorContainer("postal-castle.xml");
							container.AddComponent<SendEmailConsumer>("sec");
							container.AddComponent<PostalService>();
						});

					c.ConfigureService<PostalService>(a =>
						{
							a.WhenStarted(o => o.Start());
							a.WhenStopped(o => o.Stop());
						});
				});
			Runner.Host(cfg, args);
		}
コード例 #4
0
ファイル: Program.cs プロジェクト: JackWangCUMT/rhino-tools
        static void Main()
        {
            try
            {
                ConfigureDatabase();

                IWindsorContainer container = new WindsorContainer();
                container.AddComponent("logger",typeof(ILogger), typeof(ConsoleLoggerImpl));
                container.AddComponent("auditor", typeof (IAuditor), typeof (AuditorImpl));
                container.AddComponent("authorization", typeof (IAuthorization), typeof (AuthorizationImpl));
                container.AddComponent("repository", typeof(IRepository), typeof(RepositoryImpl));
                container.AddComponent("customer_finder", typeof (ICustomerFinder), typeof (CustomerFinderImpl));

                ICustomerFinder customerFinder = container.Resolve<ICustomerFinder>();
                ICollection<Customer> customers = customerFinder.FindCustomersByName("oren");
                foreach (Customer customer in customers)
                {
                    Console.WriteLine("Got customer: "+customer.Name);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }
        }
コード例 #5
0
 public DelayedMessages()
 {
     container = new WindsorContainer(new XmlInterpreter());
     container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility());
     container.AddComponent <HandleMessageLater>();
     container.AddComponent <ProcessInteger>();
 }
コード例 #6
0
ファイル: OutfitEngine.cs プロジェクト: tuxevil/FashionAde
        protected override void OnStart(string[] args)
        {
            storage = new WcfSessionStorage();

            log4net.Config.XmlConfigurator.Configure();

            // Create container
            IWindsorContainer container = new WindsorContainer();

            // Add Engine for the Host Service
            container.AddComponent("outfitEngineService", typeof(OutfitEngineService));
            container.AddComponent("outfitUpdaterService", typeof(OutfitUpdaterService));

            // Add the Services to the Container
            ComponentRegistrar.AddServicesTo(container);
            ComponentRegistrar.AddApplicationServicesTo(container);

            // Create the container
            ServiceLocatorInitializer.Init(container);

            // Initialize NHibernate
            NHibernateInitializer.Instance().InitializeNHibernateOnce(
                () => InitializeNHibernateSession());

            // Create Service Host
            host = new System.ServiceModel.ServiceHost(typeof(OutfitEngineService));
            host.Description.Behaviors.Add(new PerCallServiceBehavior());
            host.Open();

            hostUpdater = new SharpArch.Wcf.NHibernate.ServiceHost(typeof(OutfitUpdaterService));
            hostUpdater.Open();
        }
コード例 #7
0
		public void TestBasicOperations()
		{
			WindsorContainer container = new WindsorContainer(new DefaultConfigurationStore());

			container.AddFacility("transactionmanagement", new TransactionFacility());

			container.AddComponent("transactionmanager",
								   typeof(ITransactionManager), typeof(MockTransactionManager));

			container.AddComponent("services.customer", typeof(CustomerService));

			CustomerService service = (CustomerService)container["services.customer"];

			service.Insert("TestCustomer", "Rua P Leite, 33");

			MockTransactionManager transactionManager = (MockTransactionManager)
														container["transactionmanager"];

			Assert.AreEqual(1, transactionManager.TransactionCount);
			Assert.AreEqual(1, transactionManager.CommittedCount);
			Assert.AreEqual(0, transactionManager.RolledBackCount);

			try
			{
				service.Delete(1);
			}
			catch (Exception)
			{
				// Expected
			}

			Assert.AreEqual(2, transactionManager.TransactionCount);
			Assert.AreEqual(1, transactionManager.CommittedCount);
			Assert.AreEqual(1, transactionManager.RolledBackCount);
		}
コード例 #8
0
ファイル: Program.cs プロジェクト: fhelje/MassTransit
        private static void Main(string[] args)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.xml"));

            var cfg = RunnerConfigurator.New(c =>
            {
                c.SetServiceName("PostalService");
                c.SetDisplayName("Sample Email Service");
                c.SetDescription("we goin' postal");

                c.RunAsLocalSystem();
                c.DependencyOnMsmq();

                c.BeforeStartingServices(a =>
                {
                    var container = new WindsorContainer("postal-castle.xml");
                    container.AddComponent <SendEmailConsumer>("sec");
                    container.AddComponent <PostalService>();
                });

                c.ConfigureService <PostalService>(a =>
                {
                    a.WhenStarted(o => o.Start());
                    a.WhenStopped(o => o.Stop());
                });
            });

            Runner.Host(cfg, args);
        }
コード例 #9
0
		public void ExternalConfigurationUsage()
		{
			WindsorContainer container = new WindsorContainer( ConfigHelper.ResolvePath("../aop_castle_config.xml") );

			container.AddFacility( "aspectsharp", new AspectSharpFacility() );
			
			// Logger implementation
			container.AddComponent( "logger", typeof(ILogger), typeof(MemoryLogger) );

			// AopAlliance interceptors
			container.AddComponent( "log4netinterceptor", typeof(LoggerTraceInterceptor) );
			
			// Protocol handlers
			container.AddComponent( "protocolhandler.miranda", 
				typeof(IProtocolHandler), typeof(MirandaProtocolHandler) );
			container.AddComponent( "protocolhandler.messenger", 
				typeof(IProtocolHandler), typeof(MessengerProtocolHandler) );
			
			// using...

			ILogger logger = (ILogger) container[ typeof(ILogger) ];
			Assert.AreEqual( 0, logger.Contents.Length );

			IProtocolHandler handler = (IProtocolHandler) 
				container[ "protocolhandler.miranda" ];
			handler.Handle( "contents" );

			handler = (IProtocolHandler) container[ "protocolhandler.messenger" ];
			handler.Handle( "contents" );

			Assert.AreEqual( "Entering Handle Leaving Handle Entering Handle Leaving Handle ", 
				logger.Contents );
		}
コード例 #10
0
        static void Main()
        {
            try
            {
                ConfigureDatabase();

                IWindsorContainer container = new WindsorContainer();
                container.AddComponent("logger", typeof(ILogger), typeof(ConsoleLoggerImpl));
                container.AddComponent("auditor", typeof(IAuditor), typeof(AuditorImpl));
                container.AddComponent("authorization", typeof(IAuthorization), typeof(AuthorizationImpl));
                container.AddComponent("repository", typeof(IRepository), typeof(RepositoryImpl));
                container.AddComponent("customer_finder", typeof(ICustomerFinder), typeof(CustomerFinderImpl));

                ICustomerFinder        customerFinder = container.Resolve <ICustomerFinder>();
                ICollection <Customer> customers      = customerFinder.FindCustomersByName("oren");
                foreach (Customer customer in customers)
                {
                    Console.WriteLine("Got customer: " + customer.Name);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e);
            }
        }
コード例 #11
0
        public void ConfigureIoC(string configPath)
        {
            // create a Windsor container with various component parameters established
            var container = new WindsorContainer(configPath);

            // Replaces the default IViewEngine.
            container.AddComponent <IViewEngine, SparkViewFactory>();
            container.AddComponent <IViewActivatorFactory, WindsorViewActivator>();

            // Add anything descended from IController/Controller
            container.Register(
                AllTypes.Of <IController>()
                .FromAssembly(typeof(Global).Assembly)
                .Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLowerInvariant())));

            // Some more components from the sample
            container.AddComponent <IViewFolder, FileSystemViewFolder>();
            container.AddComponent <ISampleRepository, SampleRepository>();
            container.AddComponent <INavRepository, NavRepository>();

            // Place this container as the dependency resolver and hook it into
            // the controller factory mechanism
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));
            ViewEngines.Engines.Add(container.Resolve <IViewEngine>());
        }
コード例 #12
0
        public void Setup()
        {
            var supplier = TestSupplier.CreateNaked(session);

            supplier.CreateSampleCore(session);
            client  = TestClient.CreateNaked(session);
            address = client.CreateAddress();
            user    = client.Users.First();
            session.Save(address);
            ServiceContext.GetUserName = () => user.Login;

            var container = new WindsorContainer();

            container.AddComponent("RepositoryInterceptor", typeof(RepositoryInterceptor));
            container.AddComponent("OfferRepository", typeof(IOfferRepository), typeof(OfferRepository));
            container.AddComponent("Repository", typeof(IRepository <>), typeof(Repository <>));
            var holder = new SessionFactoryHolder();

            holder
            .Configuration
            .AddInputStream(HbmSerializer.Default.Serialize(Assembly.Load("Common.Models")));
            container.Kernel.AddComponentInstance <ISessionFactoryHolder>(holder);
            IoC.Initialize(container);
            IoC.Container.Register(
                Component.For <IInforoomOnlineService>()
                .ImplementedBy <InforoomOnlineService>()
                .Interceptors(InterceptorReference.ForType <ContextLoaderInterceptor>())
                .Anywhere,
                Component.For <ContextLoaderInterceptor>(),
                Component.For <IClientLoader>().ImplementedBy <ClientLoader>());

            service = IoC.Resolve <IInforoomOnlineService>();
        }
コード例 #13
0
ファイル: Global.cs プロジェクト: dtabuenc/spark
        public void ConfigureIoC()
        {
            // create a Windsor container with various component parameters established
            var container = new WindsorContainer(Server.MapPath("~/castle.config"));

            // Replaces the default IViewEngine.
            container.AddComponent<IViewEngine, SparkViewFactory>();
            container.AddComponent<IViewActivatorFactory, WindsorViewActivator>();

            // Add anything descended from IController/Controller
            container.Register(
                AllTypes.Of<IController>()
                    .FromAssembly(typeof (Global).Assembly)
                    .Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLowerInvariant())));

            // Some more components from the sample
            container.AddComponent<IViewFolder, FileSystemViewFolder>();
            container.AddComponent<ISampleRepository, SampleRepository>();
            container.AddComponent<INavRepository, NavRepository>();

            // Place this container as the dependency resolver and hook it into
            // the controller factory mechanism
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));
            ViewEngines.Engines.Add(container.Resolve<IViewEngine>());
        }
コード例 #14
0
        public void ExternalConfigurationUsage()
        {
            WindsorContainer container = new WindsorContainer("../aop_castle_config.xml");

            container.AddFacility("aspectsharp", new AspectSharpFacility());

            // Logger implementation
            container.AddComponent("logger", typeof(ILogger), typeof(MemoryLogger));

            // AopAlliance interceptors
            container.AddComponent("log4netinterceptor", typeof(LoggerTraceInterceptor));

            // Protocol handlers
            container.AddComponent("protocolhandler.miranda",
                                   typeof(IProtocolHandler), typeof(MirandaProtocolHandler));
            container.AddComponent("protocolhandler.messenger",
                                   typeof(IProtocolHandler), typeof(MessengerProtocolHandler));

            // using...

            ILogger logger = (ILogger)container[typeof(ILogger)];

            Assert.AreEqual(0, logger.Contents.Length);

            IProtocolHandler handler = (IProtocolHandler)
                                       container["protocolhandler.miranda"];

            handler.Handle("contents");

            handler = (IProtocolHandler)container["protocolhandler.messenger"];
            handler.Handle("contents");

            Assert.AreEqual("Entering Handle Leaving Handle Entering Handle Leaving Handle ",
                            logger.Contents);
        }
コード例 #15
0
 public static void Init(Type transactionManagerType)
 {
     IWindsorContainer container = new WindsorContainer();
     container.AddComponent("TransactionManager", typeof (ITransactionManager),
                            transactionManagerType);
     container.AddComponent("ExceptionLogger", typeof (IExceptionLogger), typeof (ExceptionLogger));
     ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
 }
コード例 #16
0
 private void AddFiltersAndControllers(WindsorContainer container)
 {
     container.AddComponent("auth.filter", typeof(CheckAuthenticationFilter));
     container.AddComponent("home", typeof(HomeController));
     container.AddComponent("dashboard", typeof(DashboardController));
     container.AddComponent("registration", typeof(RegistrationController));
     container.AddComponent("project", typeof(ProjectController));
 }
		public void RequestSingleInterfaceProxyWithoutServiceInterface()
		{
			var container = new WindsorContainer();
			container.AddComponent("standard.interceptor", typeof(StandardInterceptor));

			Assert.Throws(typeof(ComponentRegistrationException),()=>
				container.AddComponent("useSingle", typeof(CalculatorServiceWithSingleProxyBehavior)));
		}
コード例 #18
0
ファイル: ProxyTests.cs プロジェクト: ruanzx/mausch
 public void Windsor_FS()
 {
     var container = new WindsorContainer();
     container.AddComponent<TestInterceptor>();
     container.Kernel.ProxyFactory.AddInterceptorSelector(new TestInterceptorSelector());
     container.AddComponent<IComparer, ComparerFS>();
     container.Resolve<IComparer>().Compare(0, 0);
 }
コード例 #19
0
		private void AddFiltersAndControllers(WindsorContainer container)
		{
			container.AddComponent( "auth.filter", typeof(CheckAuthenticationFilter) );
			container.AddComponent( "home", typeof(HomeController) );
			container.AddComponent( "dashboard", typeof(DashboardController) );
			container.AddComponent( "registration", typeof(RegistrationController) );
			container.AddComponent( "project", typeof(ProjectController) );
		}
コード例 #20
0
 public static void Init() {
     IWindsorContainer container = new WindsorContainer();
     container.AddComponent("validator", 
         typeof(IValidator), typeof(Validator));
     container.AddComponent("entityDuplicateChecker",
         typeof(IEntityDuplicateChecker), typeof(EntityDuplicateCheckerStub));
     ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
 }
		public void ResolvingComponentIsDoneOnFirstComeBasisWhenNamesAreNotOrdered()
		{
			var windsor = new WindsorContainer();
			windsor.AddComponent<IService, Srv1>("3");
			windsor.AddComponent<IService, Srv1>("2");

			Assert.IsInstanceOf<Srv1>(windsor.Resolve<IService>());
		}
コード例 #22
0
        protected override IServiceLocator CreateServiceLocator() {
            var container = new WindsorContainer();
            Type simpleType = typeof(SimpleLogger);
            Type complexType = typeof(ComplexLogger);
            container.AddComponent(simpleType.FullName, typeof(ILogger), simpleType);
            container.AddComponent(complexType.FullName, typeof(ComplexLogger), complexType);

            return new WindsorServiceLocator(container);
        }
コード例 #23
0
            public override void Setup()
            {
                IWindsorContainer container = new WindsorContainer();
                container.AddComponent("SimpleDependency", typeof(SimpleDependency));
                container.AddComponent("IDependency", typeof(IDependency), typeof(SimpleDependency));
                container.AddComponent("NestedDependency",typeof(NestedDependency));

                _dependencyResolver = new WindsorDependencyResolver(container);
            }
コード例 #24
0
        public void WorkflowRuntimeServicesAreAdded()
        {
            _container.AddComponent("explodingtracking.service", typeof(ExplodingTrackingService));

            WorkflowRuntime runtime  = _container.Resolve <WorkflowRuntime>();
            TrackingService instance = runtime.GetService <TrackingService>();

            Assert.IsInstanceOfType(typeof(ExplodingTrackingService), instance, "Type based off of WorkflowRuntimeService should be added to workflowruntime");
        }
コード例 #25
0
		public void ShouldNotSetTheViewControllerProperty()
		{
			IWindsorContainer container = new WindsorContainer();
			container.AddComponent("controller", typeof(IController), typeof(Controller));
			container.AddComponent("view", typeof(IView), typeof(View));
			Controller controller = (Controller)container.Resolve("controller");
			Assert.IsNotNull(controller.View);
			Assert.IsNull(controller.View.Controller);
		}
コード例 #26
0
        public void InitServiceLocator()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent("duplicateChecker",
                                   typeof(IEntityDuplicateChecker), typeof(DuplicateCheckerStub));
            container.AddComponent("validator", typeof(IValidator), typeof(Validator));
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }
コード例 #27
0
ファイル: IoC-78.cs プロジェクト: nats/castle-1.0.3-mono
        public void WillIgnoreComponentsThatAreAlreadyInTheDependencyTracker_Constructor()
        {
            IWindsorContainer container = new WindsorContainer();
            container.AddComponent("chain", typeof(IChain), typeof(MyChain));
            container.AddComponent("chain2", typeof(IChain), typeof(MyChain2));

            IChain resolve = container.Resolve<IChain>("chain2");
            Assert.IsNotNull(resolve);
        }
コード例 #28
0
		public virtual void Init()
		{
			_container = new WindsorContainer(ConfigHelper.ResolvePath("../Castle.Facilities.Db4oIntegration.Tests/Castle.Facilities.Db4oIntegration.Tests.config"));	

			_container.AddFacility("transaction", new TransactionFacility());

			_container.AddComponent("beer.dao", typeof(BeerDao), typeof(BeerDao));
			_container.AddComponent("beer.dao.transactional", typeof(BeerTransactionalDao), typeof(BeerTransactionalDao));
			_container.AddComponent("beer.box", typeof(BeerBox), typeof(BeerBox));
		}
コード例 #29
0
		public void ThrowsACircularDependencyException2()
		{
			IWindsorContainer container = new WindsorContainer();
			container.AddComponent("compA", typeof(CompA));
			container.AddComponent("compB", typeof(CompB));
			container.AddComponent("compC", typeof(CompC));
			container.AddComponent("compD", typeof(CompD));

			container.Resolve("compA");
		}
コード例 #30
0
            public override void Setup()
            {
                IWindsorContainer container = new WindsorContainer();

                container.AddComponent("SimpleDependency", typeof(SimpleDependency));
                container.AddComponent("IDependency", typeof(IDependency), typeof(SimpleDependency));
                container.AddComponent("NestedDependency", typeof(NestedDependency));

                _dependencyResolver = new WindsorDependencyResolver(container);
            }
コード例 #31
0
 public void Test()
 {
     using (var container = new WindsorContainer()) {
         container.AddFacility<StartableFacility>();
         container.AddComponent<IEmailService, EmailService>();
         container.AddComponent<ICriticalService, CriticalService>();
         container.Resolve<ICriticalService>().DoStuff();
         container.Resolve<IEmailService>().SendEmail("Blah");
     }
 }
 public void ShouldResolveDecoratedComponent()
 {
     WindsorContainer container = new WindsorContainer();
     container.AddComponent("DoNothingServiceDecorator", typeof(IDoNothingService), typeof(DoNothingServiceDecorator));
     container.AddComponent("DoNothingService", typeof(IDoNothingService), typeof(DoNothingService));
     IDoNothingService service = container.Resolve<IDoNothingService>();
     Assert.IsNotNull(service);
     Assert.IsInstanceOf(typeof(DoNothingServiceDecorator), service);
     Assert.IsInstanceOf(typeof(DoNothingService), ((DoNothingServiceDecorator)service).Inner);
 }
コード例 #33
0
        public virtual void Init()
        {
            _container = new WindsorContainer(ConfigHelper.ResolvePath("../Castle.Facilities.Db4oIntegration.Tests/Castle.Facilities.Db4oIntegration.Tests.config"));

            _container.AddFacility("transaction", new TransactionFacility());

            _container.AddComponent("beer.dao", typeof(BeerDao), typeof(BeerDao));
            _container.AddComponent("beer.dao.transactional", typeof(BeerTransactionalDao), typeof(BeerTransactionalDao));
            _container.AddComponent("beer.box", typeof(BeerBox), typeof(BeerBox));
        }
コード例 #34
0
        public void can_resolve_session()
        {
            var container = new WindsorContainer();

            container.AddComponent <IDatabaseConfiguration, TestDatabaseConfiguration>();
            container.AddFacility <NhibernateFacility>();

            container.AddComponent <NeedsSession>();
            using (new SessionScope(container.Resolve <ISessionFactory>()))
                Assert.NotNull(container.Resolve <NeedsSession>());
        }
コード例 #35
0
		public void NoSingleInterfaceProxyWithAttribute()
		{
			var container = new WindsorContainer();

			container.AddComponent("standard.interceptor", typeof(StandardInterceptor));
			container.AddComponent("noSingle", typeof(ICalcService), typeof(CalculatorServiceWithoutSingleProxyBehavior));

			var calcService = (ICalcService) container["noSingle"];
			Assert.IsNotNull(calcService);
			Assert.IsTrue(calcService is IDisposable, "Service proxy should expose the IDisposable interface");
		}
コード例 #36
0
ファイル: NoResolutionTests.cs プロジェクト: ruanzx/mausch
 public void NoPropInjection()
 {
     var c = new WindsorContainer();
     c.Kernel.ComponentModelCreated += model => {
         if (model.Implementation == typeof(Service))
             model.Properties.Clear();
     };
     c.AddComponent<IServiceA, ServiceA>();
     c.AddComponent<Service>();
     Assert.IsNull(c.Resolve<Service>().Svc);
 }
コード例 #37
0
		public void RequestSingleInterfaceProxyWithAttribute()
		{
			IWindsorContainer container = new WindsorContainer();

			container.AddComponent("standard.interceptor", typeof(StandardInterceptor));
			container.AddComponent("useSingle", typeof(ICalcService), typeof(CalculatorServiceWithSingleProxyBehavior));

			ICalcService calcService = (ICalcService) container["useSingle"];
			Assert.IsNotNull(calcService);
			Assert.IsFalse(calcService is IDisposable, "Service proxy should not expose the IDisposable interface");
		}
コード例 #38
0
        protected override IServiceLocator CreateServiceLocator()
        {
            var  container   = new WindsorContainer();
            Type simpleType  = typeof(SimpleLogger);
            Type complexType = typeof(ComplexLogger);

            container.AddComponent(simpleType.FullName, typeof(ILogger), simpleType);
            container.AddComponent(complexType.FullName, typeof(ComplexLogger), complexType);

            return(new WindsorServiceLocator(container));
        }
 public void ShouldResolveDecoratedComponentFromParent()
 {
     WindsorContainer parent = new WindsorContainer();
     WindsorContainer child = new WindsorContainer();
     parent.AddChildContainer(child);
     parent.AddComponent("DoNothingServiceDecorator", typeof(IDoNothingService), typeof(DoNothingServiceDecorator));
     parent.AddComponent("DoNothingService", typeof(IDoNothingService), typeof(DoNothingService));
     child.AddComponent("DoSometingService", typeof(IDoSomethingService), typeof(DoSomethingService));
     IDoNothingService service = child.Resolve<IDoNothingService>();
     Assert.IsNotNull(service);
     Assert.IsInstanceOf(typeof(DoNothingServiceDecorator), service);
 }
コード例 #40
0
ファイル: IoC-138.cs プロジェクト: ralescano/castle
        public void TestResolveSubComponentInConstructorWithParameters()
        {
            IWindsorContainer container = new WindsorContainer();
            container.AddComponent("A", typeof(A));
            container.AddComponent("B", typeof(B));

            IDictionary parameters = new ListDictionary();
            parameters.Add("test", "bla");

            A a = container.Resolve<A>(parameters);
            Assert.IsNotNull(a);
        }
コード例 #41
0
 public static void Init()
 {
     IWindsorContainer container = new WindsorContainer();
     container.AddComponent("validator",
         typeof(IValidator), typeof(Validator));
     container.AddComponent("entityDuplicateChecker",
         typeof(IEntityDuplicateChecker), typeof(EntityDuplicateCheckerStub));
     container.AddComponent("repositoryWithTypedId",
         typeof(IRepositoryWithTypedId<,>), typeof(RepositoryWithTypedId<,>));
     container.AddComponent("userRepository", typeof(IUserRepository), typeof(UserRepository));
     ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
 }
コード例 #42
0
        public void IOC_Castle()
        {
            IWindsorContainer container = new WindsorContainer();
                container.AddComponent<PersonLogicBTestable>();
                container.AddComponent<ILogger,FakeLogger>();
                container.AddComponent<IPersonValidator,MyFakeValidator>();

            PersonLogicBTestable logic =
                container.Resolve<PersonLogicBTestable>();

            bool canPurchase = logic.CanPurchase(new Person());
            Assert.IsFalse(canPurchase);
        }
コード例 #43
0
        public static void Init()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent("validator",
                                   typeof(IValidator), typeof(Validator));
            container.AddComponent("entityDuplicateChecker",
                                   typeof(IEntityDuplicateChecker), typeof(EntityDuplicateCheckerStub));
            container.AddComponent("repositoryWithTypedId",
                                   typeof(IRepositoryWithTypedId <,>), typeof(RepositoryWithTypedId <,>));
            container.AddComponent("userRepository", typeof(IUserRepository), typeof(UserRepository));
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }
コード例 #44
0
        public void  Cannot_resolve_a_dependency_from_a_parent_container_under_certain_circumstances()
        {
            WindsorContainer parent = new WindsorContainer();
            WindsorContainer child = new WindsorContainer();

            parent.AddChildContainer(child);

            parent.AddComponent("service", typeof(IParentService), typeof(ParentService));
            child.AddComponent("service1", typeof(IChildService1), typeof(ChildService1));
            child.AddComponent("service2", typeof(IChildService2), typeof(ChildService2));


            child.Resolve<IChildService1>();
        }
コード例 #45
0
ファイル: Program.cs プロジェクト: rh/spikes
        private static void Main()
        {
            IWindsorContainer container = new WindsorContainer();
            // The container is needed by SecurityInterceptor
            container.Kernel.AddComponentInstance("container", typeof(IWindsorContainer), container);

            // SubDependencyResolver decides which implementation of ISecurityService should be returned,
            // but both implementations have to be registered
            container.Kernel.Resolver.AddSubResolver(new SubDependencyResolver(container.Kernel));
            container.AddComponent<ISecurityService, SecureSecurityService>("security1");
            container.AddComponent<ISecurityService, InsecureSecurityService>("security2");

            // ModelInterceptorsSelector selects the interceptors to be added, but these have to be registered
            container.Kernel.ProxyFactory.AddInterceptorSelector(new ModelInterceptorsSelector());
            container.AddComponent("logging.interceptor", typeof(LoggingInterceptor));
            container.AddComponent("security.interceptor", typeof(SecurityInterceptor));

            // Every resolved instance of Person will be the same. It represents the 'currently logged-in user'
            container.AddComponentLifeStyle("user", typeof(Person), LifestyleType.Singleton);
            // This service needs to be transient or the SubDependencyResolver will only be called once
            container.AddComponentLifeStyle("foo", typeof(Service), LifestyleType.Transient);

            Person person = container.Resolve<Person>();

            person.UserName = "******";
            // This FooService will be instantiated with an InsecureSecurityService
            Service service1 = container.Resolve<Service>();
            // Notice the output of LoggingInterceptor and the output of Service itself,
            // which depends upon the implementation of ISecurityService
            service1.Do();

            // Pretend another user has logged in
            person.UserName = "******";
            // This FooService will be instantiated with an SecureSecurityService
            Service service2 = container.Resolve<Service>();

            try
            {
                // SecurityInterceptor will throw here
                service2.Do();
            }
            catch (SecurityException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine();
            Console.WriteLine("Press [Enter] to continue...");
            Console.ReadLine();
        }
コード例 #46
0
        public void Should_resolve_child_from_childs_container()
        {
            WindsorContainer parent = new WindsorContainer();
            WindsorContainer child = new WindsorContainer();

            parent.AddChildContainer(child);

            parent.AddComponent("service1", typeof(IParentService), typeof(ParentService));
            parent.AddComponent("service3", typeof(IChildService2), typeof(ChildService2));
            child.AddComponent("service2", typeof(IParentService), typeof(AnotherParentService));

			IChildService2 resolve = child.Resolve<IChildService2>();
            Assert.IsInstanceOf(typeof(AnotherParentService),resolve.Parent);
        }
コード例 #47
0
        public void IOC_Castle()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent <PersonLogicBTestable>();
            container.AddComponent <ILogger, FakeLogger>();
            container.AddComponent <IPersonValidator, MyFakeValidator>();

            PersonLogicBTestable logic =
                container.Resolve <PersonLogicBTestable>();

            bool canPurchase = logic.CanPurchase(new Person());

            Assert.IsFalse(canPurchase);
        }
コード例 #48
0
        public void SimpleCase()
        {
            String contents =
                "import Castle.Facilities.AspectSharp.Tests.Components in Castle.Facilities.AspectSharp.Tests " +
                "import Castle.Facilities.AspectSharp.Tests.Interceptors in Castle.Facilities.AspectSharp.Tests " +
                " " +
                " aspect MyAspect for SimpleService " +
                "   " +
                "   pointcut method|property(*)" +
                "     advice(LoggerInterceptor)" +
                "   end" +
                "   " +
                " end ";

            MutableConfiguration config = new MutableConfiguration("facility", contents);

            DefaultConfigurationStore store = new DefaultConfigurationStore();

            store.AddFacilityConfiguration("aop", config);

            WindsorContainer container = new WindsorContainer(store);

            container.AddFacility("aop", new AspectSharpFacility());

            container.AddComponent("comp1", typeof(SimpleService));

            SimpleService service = container[typeof(SimpleService)] as SimpleService;

            service.DoSomething();
            service.DoSomethingElse();

            Assert.AreEqual("Enter DoSomething\r\nEnter DoSomethingElse\r\n",
                            LoggerInterceptor.Messages.ToString());
        }
コード例 #49
0
        private IContainer build_the_container()
        {
            IWindsorContainer windsor_container = new WindsorContainer();

            infrastructure.logging.ILog nant_logger    = new NAntLogger(this);
            infrastructure.logging.ILog log4net_logger = new Log4NetLogger(the_logger);
            infrastructure.logging.ILog multi_logger   = new MultipleLogger(new List <infrastructure.logging.ILog> {
                nant_logger, log4net_logger
            });

            windsor_container.Kernel.AddComponentInstance <infrastructure.logging.ILog>(multi_logger);
            windsor_container.AddComponent <IFileSystemAccess, WindowsFileSystemAccess>();
            windsor_container.AddComponent <ILogFactory, MultipleLoggerLogFactory>();

            return(new infrastructure.containers.custom.WindsorContainer(windsor_container));
        }
コード例 #50
0
        public static void Init()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent("validator",
                                   typeof(IValidator), typeof(Validator));
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }
コード例 #51
0
 public CanSendMsgsFromOneWayBus()
 {
     container = new WindsorContainer(new XmlInterpreter());
     container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility());
     container.AddComponent <StringConsumer>();
     StringConsumer.Value = null;
     StringConsumer.Event = new ManualResetEvent(false);
 }
コード例 #52
0
        public void TransientComponents()
        {
            String contents =
                "import Castle.Facilities.AspectSharp.Tests.Components in Castle.Facilities.AspectSharp.Tests " +
                "import Castle.Facilities.AspectSharp.Tests.Interceptors in Castle.Facilities.AspectSharp.Tests " +
                " " +
                " aspect MyAspect for AnotherService " +
                "   " +
                "   pointcut method|property(*)" +
                "     advice(LoggerInterceptor)" +
                "   end" +
                "   " +
                " end ";

            MutableConfiguration config = new MutableConfiguration("facility", contents);

            DefaultConfigurationStore store = new DefaultConfigurationStore();

            store.AddFacilityConfiguration("aop", config);

            WindsorContainer container = new WindsorContainer(store);

            container.AddFacility("aop", new AspectSharpFacility());

            container.AddComponent("interceptor1", typeof(CastleSimpleInterceptor));
            container.AddComponent("comp1", typeof(SimpleService));
            container.AddComponent("comp2", typeof(IAnotherService), typeof(AnotherService));

            for (int i = 1; i < 10000; i++)
            {
                LoggerInterceptor.Messages.Length = 0;

                IAnotherService service = container[typeof(IAnotherService)] as IAnotherService;
                service.Name = "hammett";
                service.StartWork();

                Assert.AreEqual("Enter set_Name\r\nEnter StartWork\r\n",
                                LoggerInterceptor.Messages.ToString());

                CastleSimpleInterceptor interceptor =
                    container[typeof(CastleSimpleInterceptor)] as CastleSimpleInterceptor;

                Assert.AreEqual(2 * i, interceptor.Executions);
            }
        }
コード例 #53
0
        public void SetUp()
        {
            var container = new WindsorContainer();

            DependencyResolver.InitializeWith(new WindsorDependencyResolver(container));
            container.AddComponent("transaction.manager", typeof(ITransactionManager), typeof(TestITransactionManager));
            manager   = DependencyResolver.Resolver.GetImplementationOf <ITransactionManager>();
            attribute = new MvcTransactionAttribute();
        }
コード例 #54
0
ファイル: Program.cs プロジェクト: tuxevil/FashionAde
        static void Main(string[] args)
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();

                // Create container
                IWindsorContainer container = new WindsorContainer();

                // Add Engine for the Host Service
                container.AddComponent("outfitEngineService", typeof(OutfitEngineService));
                container.AddComponent("outfitUpdaterService", typeof(OutfitUpdaterService));

                // Add the Services to the Container
                ComponentRegistrar.AddServicesTo(container);
                ComponentRegistrar.AddApplicationServicesTo(container);

                // Create the container
                ServiceLocatorInitializer.Init(container);

                // Initialize NHibernate
                NHibernateInitializer.Instance().InitializeNHibernateOnce(
                    () => InitializeNHibernateSession());

                System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(OutfitEngineService));
                host.Description.Behaviors.Add(new PerCallServiceBehavior());
                host.Open();

                ServiceHost host2 = new ServiceHost(typeof(OutfitUpdaterService));
                host2.Open();

                Console.WriteLine("Service started...");
                Console.ReadLine();

                host.Close();
                host2.Close();

                Console.WriteLine("Service stopped...");
                Console.ReadLine();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
        }
コード例 #55
0
ファイル: App.cs プロジェクト: qinfengzhu/StudyCastle
        public static void Main()
        {
            IWindsorContainer container = new WindsorContainer(new XmlInterpreter("../BasicUsage.xml"));

            container.AddComponent("newsletter",
                                   typeof(INewsletterService), typeof(SimpleNewsletterService));
            container.AddComponent("smtpemailsender",
                                   typeof(IEmailSender), typeof(SmtpEmailSender));
            container.AddComponent("templateengine",
                                   typeof(ITemplateEngine), typeof(NVelocityTemplateEngine));

            String[] friendsList = new String[] { "john", "steve", "david" };

            // Ok, start the show

            INewsletterService service = (INewsletterService)container["newsletter"];

            service.Dispatch("hammett at gmail dot com", friendsList, "merryxmas");
        }
コード例 #56
0
        public void ShouldThrow_WhenComponentIsNotIModelBinder()
        {
            var container = new WindsorContainer();

            container.AddComponent <object>("testmodelbinder");

            var binder = new WindsorModelBinder(container);

            binder.BindModel(new ControllerContext(), _context);
        }
コード例 #57
0
    public void FactoryTest()
    {
        var container = new WindsorContainer();

        container.AddFacility <FactorySupportFacility>();
        container.AddComponent <IDataFactory, DataFactory>();
        container.Register(Component.For <IDataService>().UsingFactory((IDataFactory f) => f.Service));
        var service = container.Resolve <IDataService>();

        Assert.IsInstanceOfType(typeof(DataService), service);
    }
コード例 #58
0
        public void CanReturnServiceIfInitializedAndRegistered()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent("validator", typeof(IValidator), typeof(Validator));
            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));

            IValidator validatorService = SafeServiceLocator <IValidator> .GetService();

            Assert.That(validatorService, Is.Not.Null);
        }
コード例 #59
0
        protected override void InitializeServiceLocator()
        {
            container = new WindsorContainer();
            var sl = new WindsorServiceLocator(container);

            container.Register(Component.For <IServiceLocator>().Instance(sl));
            ServiceLocator.SetLocatorProvider(() => sl);
            container.AddComponent <IInvoiceTotalCalculator, SumAndTaxTotalCalculator>();
            container.AddComponentLifeStyle(typeof(Invoice).FullName,
                                            typeof(IInvoice), typeof(Invoice), LifestyleType.Transient);
        }
コード例 #60
0
        public void ShouldResolveTheCorrectBinder_WhenBinderExists()
        {
            IWindsorContainer container = new WindsorContainer();

            container.AddComponent <IModelBinder, TestModelBinder>("testmodelbinder");

            var binder = new WindsorModelBinder(container);

            var value = binder.BindModel(new ControllerContext(), _context);

            Assert.That(value, Is.EqualTo("TestResult"));
        }