Beispiel #1
0
        public void ResolveInspections_NoException()
        {
            var vbeBuilder      = new MockVbeBuilder();
            var ide             = vbeBuilder.Build().Object;
            var addin           = new Mock <IAddIn>().Object;
            var initialSettings = new GeneralSettings {
                SourceControlEnabled = true
            };

            IWindsorContainer container = null;

            try
            {
                try
                {
                    container = new WindsorContainer().Install(new RubberduckIoCInstaller(ide, addin, initialSettings));
                }
                catch (Exception exception)
                {
                    Assert.Inconclusive($"Unable to register. {Environment.NewLine} {exception}");
                }

                var inspections = container.ResolveAll <IInspection>();

                //This test does not need an assert because it tests that no exception has been thrown.
            }
            finally
            {
                container?.Dispose();
            }
        }
        public void TearDown()
        {
            _windsorContainer.Dispose();

            _mutex.ReleaseMutex();
            _mutex.Dispose();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Install(FromAssembly.This());

            bool logToNewRelic = args.Length > 1 && args[1].ToLower() == "newrelic";

            if (logToNewRelic)
            {

                container.Register(Component.For<ILogStatisticsRepository>()
                .ImplementedBy<NewRelicLogStatisticsRepository>()
                .IsDefault()
                .Named("WriteToNewRelic")
                .LifestyleTransient());

            }
            else
            {
                container.Register(Component.For<ILogStatisticsRepository>()
                .ImplementedBy<FileLogStatisticsRepository>()
                .IsDefault()
                .Named("WriteToFile")
                .LifestyleTransient());
            }

            var startProgram = container.Resolve<StartProgram>();
            startProgram.Start(args);
            container.Dispose();
        }
        static void Main(string[] args)
        {
            var container = new WindsorContainer(new XmlInterpreter()).Install(FromAssembly.This());
            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));

            HostFactory.Run(r =>
            {
                r.Service<IScheduleLimIntegration>(s =>
                {
                    s.ConstructUsing(name => new ScheduleWorker(container));
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc =>
                    {
                        tc.End();
                        container.Release(tc);
                        container.Dispose();
                    });
                });
                r.RunAsLocalSystem();

                r.SetDescription(System.Configuration.ConfigurationManager.AppSettings["service/config/description"]);
                r.SetDisplayName(System.Configuration.ConfigurationManager.AppSettings["service/config/displayName"]);
                r.SetServiceName(System.Configuration.ConfigurationManager.AppSettings["service/config/name"]);
            });
        }
        private void DiscoverServices(string sectionKey)
        {
            //加载服务
            var windsorContainer = new WindsorContainer(new XmlInterpreter(new ConfigResource(sectionKey)));

            //如果容易为空,则不加载
            if (windsorContainer.Kernel.GraphNodes.Length > 0)
            {
                var models = GetComponentModels <ServiceContractAttribute>(windsorContainer);
                foreach (var model in models)
                {
                    //注册服务
                    var component = Component.For(model.Services.First()).Named(model.Name).ImplementedBy(model.Implementation);
                    if (model.LifestyleType == LifestyleType.Undefined)
                    {
                        component = component.LifeStyle.Singleton;
                    }
                    else
                    {
                        component = component.LifeStyle.Is(model.LifestyleType);
                    }

                    container.Register(component);
                }

                //销毁资源
                windsorContainer.Dispose();
            }
        }
Beispiel #6
0
        static void Main()
        {
            var container = new WindsorContainer()
                .Register(Component.For<IHandleMessages<GetGreetingReply>>()
                              .ImplementedBy<GetGreetingReplyHandler>()
                              .LifestyleTransient());

            var bus = Configure.With(new CastleWindsorContainerAdapter(container))
                .Logging(l => l.None()) // disable logging to avoid polluting the console
                .Transport(t => t.UseMsmq("IntegrationSample.Client.input"))
                .Routing(d => d.TypeBased().MapAssemblyOf<GetGreetingRequest>("IntegrationSample.IntegrationService.input"))
                .Start();

            Console.WriteLine("Press R to request a greeting and Q to quit...");

            var keepRunning = true;
            do
            {
                var key = Console.ReadKey(true);

                switch (char.ToLower(key.KeyChar))
                {
                    case 'r':
                        bus.Send(new GetGreetingRequest()).Wait();
                        break;

                    case 'q':
                        keepRunning = false;
                        break;
                }
            } while (keepRunning);

            container.Dispose();
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.AddFacility <TypedFactoryFacility>();

            container.Install(new LogInstaller());

            container.Register(
                Component.For <IIntegrationEventHandlerFactory>().AsFactory(new IntegrationEventHandlerComponentSelector()),

                Component.For <IEventBusSubscriptionsManager>()
                .ImplementedBy <InMemoryEventBusSubscriptionsManager>(),

                Component.For <IRabbitMQPersistentConnection>()
                .ImplementedBy <DefaultRabbitMQPersistentConnection>(),

                Component.For <IEventBus>()
                .ImplementedBy <EventBusRabbitMQ>()
                .DependsOn(new { queueName = "LogIntegrationEvent" }),

                Component.For <LogIntegrationEventHandler>());

            var x = container.Resolve <IEventBus>();

            x.Subscribe <LogIntegrationEvent, LogIntegrationEventHandler>();

            x.StartConsumerChannel();

            Console.ReadLine();

            container.Dispose();
        }
Beispiel #8
0
 public void Teardown()
 {
     if (_container != null)
     {
         _container.Dispose();
     }
 }
Beispiel #9
0
        private static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            var client = container.Resolve<IQuilt4NetClient>();
            client.WebApiClient.WebApiRequestEvent += WebApiClientWebApiRequestEvent;
            client.WebApiClient.WebApiResponseEvent += WebApiClient_WebApiResponseEvent;
            client.WebApiClient.AuthorizationChangedEvent += WebApiClient_AuthorizationChangedEvent;

            var business1 = container.Resolve<ISomeBusiness1>();
            var business2 = container.Resolve<ISomeBusiness2>();

            try
            {
                business1.Execute();
                business2.Execute();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception: " + exception.Message);
            }

            //business1.Dispose();
            container.Dispose();

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Beispiel #10
0
        private static void ExecuteConverter(WindsorContainer container, Options o)
        {
            var converter = container.Resolve <MainConverter>();

            if (!Directory.Exists(o.OutputFolder))
            {
                Directory.CreateDirectory(o.OutputFolder);
            }

            if (!Directory.Exists(Path.Combine(o.OutputFolder, "disk")))
            {
                Directory.CreateDirectory(Path.Combine(o.OutputFolder, "disk"));
            }


            var sourcePath = Path.GetDirectoryName(Path.GetFullPath(o.InputFile));

            FileExtensions.SetSourceFolder(sourcePath);

            try
            {
                converter.Convert();
                container.Release(converter); // disposes objects
                container.Dispose();
            }
            catch (ConversionException ex)
            {
                Console.WriteLine("ERROR converting " + o.InputFile + ":");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Level has been partially generated");
            }
        }
        protected virtual void LoadPatches() {
            patches = new List<IMvcPatch>();
            var patchIocFile = TargetFileSystem.ReadXml("ioc/patches.config", null,
                                                        new ReadXmlOptions{Merge = true});
            if (patchIocFile == null){
                patchIocFile = "<configuration />";
            }
            try{
                var patchIocResource = new StaticContentResource(patchIocFile);
                if (null != patchIocFile){

                    var container = new WindsorContainer(new XmlInterpreter(patchIocResource));
                    try{
                        foreach (var patch in container.ResolveAll<IMvcPatch>()){
                            patch.FileSystem = FileSystem;
                            patch.Manager = this;
                            patch.Identity = new SimplePackageIdentity(patch.Code);
                            patches.Add(patch);
                        }
                    }
                    finally{
                        container.Dispose();
                    }
                }
            }catch(Exception ex){
                throw new Exception("error in config:\r\n"+patchIocFile,ex);
            }
        }
        public void ResolvingPooledComponentSample()
        {
            IWindsorContainer container = new WindsorContainer();

            container.Register(
                Component.For<IRepository<Client>>().ImplementedBy<ClientRepository>().LifeStyle.PooledWithSize(2, 4));

            // Two instances will be created when the component is first requested
            var instanceA = container.Resolve<IRepository<Client>>();
            var instanceB = container.Resolve<IRepository<Client>>();

            // The two instances will be marked as 'not in use' and will be available for subsequent requests
            container.Release(instanceA);
            container.Release(instanceB);

            // Same two instances will be returned
            var instanceC = container.Resolve<IRepository<Client>>();
            var instanceD = container.Resolve<IRepository<Client>>();

            // Two more instances will be created and added to the pool
            var instanceE = container.Resolve<IRepository<Client>>();
            var instanceF = container.Resolve<IRepository<Client>>();

            container.Dispose();
        }
        public async Task CreateNewShip()
        {
            var ioCContainer = new WindsorContainer();

            _RegisterComponents(ioCContainer);

            var unitOfWork = ioCContainer.Resolve <NhibernateUnitOfWork>();

            try
            {
                unitOfWork.BeginTransaction();

                try
                {
                    var shipController  = ioCContainer.Resolve <ShipController>();
                    var generatedShipId = await shipController.CreateNewShipAsync(shipName : "lady", tonnage : 10m);

                    Console.WriteLine($"Create new ship command was executed by command executor injected into ShipController. Generated ship id: {generatedShipId}");

                    await unitOfWork.CommitAsync();
                }
                catch
                {
                    await unitOfWork.RollbackAsync();

                    throw;
                }
            }
            finally
            {
                ioCContainer.Release(unitOfWork);
            }

            ioCContainer.Dispose();
        }
 private void button1_Click(object sender, EventArgs e)
 {
     IWindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
     IJobRunMgr jobRunMgr = container.Resolve<IJobRunMgr>("JobRunMgr.service");
     jobRunMgr.RunBatchJobs(container);
     container.Dispose();
 }
Beispiel #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting");

            Castle.Zmq.Context.EnsureZmqLibrary();
            Castle.Zmq.LogAdapter.LogEnabled = true;
            Castle.Zmq.LogAdapter.LogDebugFn = (scope, msg) => Console.WriteLine("Debug {0}: {1}", scope, msg);
            Castle.Zmq.LogAdapter.LogErrorFn = (scope, msg) => Console.WriteLine("Error {0}: {1}", scope, msg);


            _containerServer = new WindsorContainer(new XmlInterpreter("config_server.config"));

            _containerServer.Register(Component.For <IRemoteServ1>().ImplementedBy <RemoteServImpl>());


            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Console.WriteLine("Disposing");

                _containerServer.Dispose();
            };

            Console.WriteLine("Started");
            Thread.CurrentThread.Join();
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            _containerClient = new WindsorContainer(new XmlInterpreter("config_client.config"));
            _containerServer = new WindsorContainer(new XmlInterpreter("config_server.config"));

            _containerServer.Register(Component.For <IRemoteServ1>().ImplementedBy <RemoteServImpl>());
            _containerClient.Register(Component.For <IRemoteServ1>());

            try
            {
                var service = _containerClient.Resolve <IRemoteServ1>();

                InvokeBatch(service);
            }
            finally
            {
                Console.WriteLine("Disposing client");
                _containerClient.Dispose();

                Console.WriteLine("Disposing server");
                _containerServer.Dispose();

                Console.WriteLine("Disposed");
            }
        }
Beispiel #17
0
		static void Main(string[] args)
		{
			_containerClient = new WindsorContainer(new XmlInterpreter("config_client.config"));
			_containerServer = new WindsorContainer(new XmlInterpreter("config_server.config"));

			_containerServer.Register(Component.For<IRemoteServ1>().ImplementedBy<RemoteServImpl>());
			_containerClient.Register(Component.For<IRemoteServ1>());

			try
			{
				var service = _containerClient.Resolve<IRemoteServ1>();

				InvokeBatch(service);
			}
			finally
			{
				Console.WriteLine("Disposing client");
				_containerClient.Dispose();

				Console.WriteLine("Disposing server");
				_containerServer.Dispose();

				Console.WriteLine("Disposed");
			}
		}
Beispiel #18
0
        static void Main()
        {
            var container = new WindsorContainer()
                .Register(Component.For<IHandleMessages<GetGreetingReply>>()
                              .ImplementedBy<GetGreetingReplyHandler>()
                              .LifestyleTransient());

            var bus = Configure.With(new WindsorContainerAdapter(container))
                .Logging(l => l.None()) // disable logging to avoid polluting the console
                .Transport(t => t.UseMsmqAndGetInputQueueNameFromAppConfig())
                .MessageOwnership(d => d.FromRebusConfigurationSection())
                .CreateBus().Start();

            Console.WriteLine("Press R to request a greeting and Q to quit...");

            var keepRunning = true;
            do
            {
                var key = Console.ReadKey(true);

                switch (char.ToLower(key.KeyChar))
                {
                    case 'r':
                        bus.Send(new GetGreetingRequest());
                        break;

                    case 'q':
                        keepRunning = false;
                        break;
                }
            } while (keepRunning);

            container.Dispose();
        }
Beispiel #19
0
        static void Main()
        {
            var container = new WindsorContainer()
                            .Register(Component.For <IHandleMessages <GetGreetingReply> >()
                                      .ImplementedBy <GetGreetingReplyHandler>()
                                      .LifestyleTransient());

            var bus = Configure.With(new WindsorContainerAdapter(container))
                      .Logging(l => l.None()) // disable logging to avoid polluting the console
                      .Transport(t => t.UseMsmqAndGetInputQueueNameFromAppConfig())
                      .DetermineEndpoints(d => d.FromRebusConfigurationSection())
                      .CreateBus().Start();

            Console.WriteLine("Press R to request a greeting and Q to quit...");

            var keepRunning = true;

            do
            {
                var key = Console.ReadKey(true);

                switch (char.ToLower(key.KeyChar))
                {
                case 'r':
                    bus.Send(new GetGreetingRequest());
                    break;

                case 'q':
                    keepRunning = false;
                    break;
                }
            } while (keepRunning);

            container.Dispose();
        }
Beispiel #20
0
 public static void Dispose()
 {
     if (_windsorContainer != null)
     {
         _windsorContainer.Dispose();
     }
 }
Beispiel #21
0
        static void Main()
        {
            var container = new WindsorContainer()
                            .Register(Component.For <IHandleMessages <GetGreetingReply> >()
                                      .ImplementedBy <GetGreetingReplyHandler>()
                                      .LifestyleTransient());

            var bus = Configure.With(new CastleWindsorContainerAdapter(container))
                      .Logging(l => l.None()) // disable logging to avoid polluting the console
                      .Transport(t => t.UseMsmq("IntegrationSample.Client.input"))
                      .Routing(d => d.TypeBased().MapAssemblyOf <GetGreetingRequest>("IntegrationSample.IntegrationService.input"))
                      .Start();

            Console.WriteLine("Press R to request a greeting and Q to quit...");

            var keepRunning = true;

            do
            {
                var key = Console.ReadKey(true);

                switch (char.ToLower(key.KeyChar))
                {
                case 'r':
                    bus.Send(new GetGreetingRequest()).Wait();
                    break;

                case 'q':
                    keepRunning = false;
                    break;
                }
            } while (keepRunning);

            container.Dispose();
        }
Beispiel #22
0
		static void Main(string[] args)
		{
			Console.WriteLine("Starting");

			Castle.Zmq.Context.EnsureZmqLibrary();
			Castle.Zmq.LogAdapter.LogEnabled = true;
			Castle.Zmq.LogAdapter.LogDebugFn = (scope, msg) => Console.WriteLine("Debug {0}: {1}", scope, msg);
			Castle.Zmq.LogAdapter.LogErrorFn = (scope, msg) => Console.WriteLine("Error {0}: {1}", scope, msg);


			_containerServer = new WindsorContainer(new XmlInterpreter("config_server.config"));

			_containerServer.Register(Component.For<IRemoteServ1>().ImplementedBy<RemoteServImpl>());


			Console.CancelKeyPress += (sender, eventArgs) =>
			{
				Console.WriteLine("Disposing");

				_containerServer.Dispose();
			};

			Console.WriteLine("Started");
			Thread.CurrentThread.Join();
		}
 protected void Application_End(object sender, EventArgs e)
 {
     if (_container != null)
     {
         _container.Dispose();
     }
 }
Beispiel #24
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var contenedor = new WindsorContainer();

            try
            {
                Logging.Configurar();

                contenedor.Install(FromAssembly.This());

                contenedor.Resolve <IVentana>().Mostrar();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex);
            }
            finally
            {
                try
                {
                    contenedor.Dispose();
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error al liberar");
                }

                Current.Shutdown();
            }
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            Log4NetLogger.Use("log4net.config");

            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            HostFactory.Run(config =>
            {
                config.RunAsNetworkService();

                config.SetDescription(Settings.Default.ServiceDescription);
                config.SetServiceName(Settings.Default.ServiceName);
                config.SetDisplayName(Settings.Default.ServiceDisplayName);

                config.Service <ServiceControl>(service =>
                {
                    service.ConstructUsing(builder => container.Resolve <ServiceControl>());

                    service.WhenStarted((serviceControl, hostControl) => serviceControl.Start(hostControl));

                    service.WhenStopped((serviceControl, hostControl) =>
                    {
                        var result     = serviceControl.Stop(hostControl);
                        var serviceBus = container.Resolve <IServiceBus>();

                        serviceBus.Dispose();
                        container.Dispose();

                        return(result);
                    });
                });
            });
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();
            var kernel    = container.Kernel;

            kernel.Resolver.AddSubResolver(new CollectionResolver(kernel));
            kernel.AddFacility <TypedFactoryFacility>();
            container.Install(FromAssembly.This());
            //OrderShipperFactory.CreationClosure = () => container.Resolve<IOrderShipper>();

            // Leave one of the use cases uncommented

            // 1. First use case
            container.Register(Component.For <IOrderShipper>().ImplementedBy <OrderShipper>().LifestyleTransient());

            // 2. Second use case with lazy order shipper
            //container.Register(Component.For<IOrderShipper>().ImplementedBy<LazyOrderShipper>().LifestyleTransient());

            var config = new HttpSelfHostConfiguration("http://localhost:6666");

            config.ServiceResolver.SetResolver(new WindsorDependencyResolver(container));
            config.Routes.MapHttpRoute("defualt", "{controller}/{id}", new { id = RouteParameter.Optional });

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("The server is running.");
                Console.ReadLine();
            }

            container.Dispose();
            GC.Collect();
        }
Beispiel #27
0
 protected void Application_End()
 {
     if (container != null)
     {
         container.Dispose();
     }
 }
        public void ResolvingPerThreadComponents_NewInstanceIsCreatedForEachThread()
        {
            IWindsorContainer container = new WindsorContainer();

             container.Register(
                 Component.For<IRepository<Client>>().ImplementedBy<ClientRepository>().LifeStyle.PerThread);

             Task firstTask = Task.Factory.StartNew(() =>
             {
                 var repository = container.Resolve<IRepository<Client>>();
                 var secondRepository = container.Resolve<IRepository<Client>>();

                 Assert.AreSame(repository, secondRepository);
             });

             Task secondTask = Task.Factory.StartNew(() =>
             {
                 var repository = container.Resolve<IRepository<Client>>();
                 var secondRepository = container.Resolve<IRepository<Client>>();

                 Assert.AreSame(repository, secondRepository);
             });

             Task.WaitAll(firstTask, secondTask);

             container.Dispose();
        }
Beispiel #29
0
        public static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Register (
                Component.For<ManagerService>()
                    .LifeStyle.Singleton);

            container.Register (
                Component.For<UnmanagedService>()
                    .Interceptors<ManagerService>());

            var managerService = container.Resolve<ManagerService>();
            managerService.Start ();

            var unmanagedSvc = container.Resolve<UnmanagedService>();
            unmanagedSvc.Start ();

            Console.WriteLine ("Press enter to stop the service");
            Console.ReadLine ();

            managerService.Stop ();
            unmanagedSvc.Stop ();

            container.Dispose ();
        }
        public override TestResult DoTest(ITestCase testCase, int testCasesNumber, bool singleton)
        {
            var result = new TestResult { Singleton = singleton, TestCasesNumber = testCasesNumber };
            var sw = new Stopwatch();

            var c = new WindsorContainer();
            if (singleton)
            {
                sw.Start();
                c = (WindsorContainer)testCase.SingletonRegister(c);
                sw.Stop();
            }
            else
            {
                sw.Start();
                c = (WindsorContainer)testCase.TransientRegister(c);
                sw.Stop();
            }
            result.RegisterTime = sw.ElapsedMilliseconds;

            sw.Reset();
            result.ResolveTime = DoResolve(sw, testCase, c, testCasesNumber, singleton);

            c.Dispose();

            return result;
        }
        public async Task Should_support_the_test_harness()
        {
            var container = new WindsorContainer()
                            .AddMassTransitInMemoryTestHarness(cfg =>
            {
                cfg.AddConsumer <PingRequestConsumer>();
            });

            var harness = container.Resolve <InMemoryTestHarness>();

            await harness.Start();

            try
            {
                var bus = container.Resolve <IBus>();

                IRequestClient <PingMessage> client = bus.CreateRequestClient <PingMessage>();

                await client.GetResponse <PongMessage>(new PingMessage());

                Assert.That(await harness.Consumed.Any <PingMessage>());
            }
            finally
            {
                await harness.Stop();

                container.Dispose();
            }
        }
Beispiel #32
0
        public static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Register(
                Component.For <ManagerService>()
                .LifeStyle.Singleton);

            container.Register(
                Component.For <UnmanagedService>()
                .Interceptors <ManagerService>());

            var managerService = container.Resolve <ManagerService>();

            managerService.Start();

            var unmanagedSvc = container.Resolve <UnmanagedService>();

            unmanagedSvc.Start();

            Console.WriteLine("Press enter to stop the service");
            Console.ReadLine();

            managerService.Stop();
            unmanagedSvc.Stop();

            container.Dispose();
        }
Beispiel #33
0
        static void Main()
        {
            _container = new WindsorContainer();
            _container.Install(FromAssembly.This());
            _game              = _container.Resolve <IGame>();
            _game.SendMessage += RenderMessage;
            IStrategy _strategy = _container.Resolve <IStrategy> ();

            _strategy.SubscribeToGame(_game);
            Task.Factory.StartNew(() => _game.Start());
            _window             = new RenderWindow(VideoMode.DesktopMode, "Test");
            _window.Closed     += OnClosed;
            _window.KeyPressed += OnKeyPressed;
            _renderer           = new Renderer(_window);
            while (_window.IsOpen())
            {
                _window.DispatchEvents();
                _window.Clear();
                _renderer.RenderCalendar(_game.Calendar);
                if (_game.Scene != null)
                {
                    _renderer.RenderScene(_game.Scene);
                }
                _renderer.RenderMessage(_message);

                _window.Display();
            }

            _container.Dispose();
            Console.ReadKey();
        }
Beispiel #34
0
 protected void Application_End()
 {
     if (_windsorContainer != null)
     {
         _windsorContainer.Dispose();
     }
 }
        static void Main(string[] args)
        {
          
            var container = new WindsorContainer(new XmlInterpreter()).Install(FromAssembly.This());
            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));

            HostFactory.Run(x =>
            {
                x.Service<ICacheWorker>(s =>
                {
                    s.ConstructUsing(name => new CacheWorker(container));
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc =>
                    {
                        tc.End();
                        container.Release(tc);
                        container.Dispose();
                    });
                });
                x.RunAsLocalSystem();

                x.SetDescription(CachingConfiguration.ServiceDescription);
                x.SetDisplayName(CachingConfiguration.ServiceDisplayName);
                x.SetServiceName(CachingConfiguration.ServiceName);
            });
        }
Beispiel #36
0
        public void ResolveRubberduckParserState_NoException()
        {
            var vbeBuilder      = new MockVbeBuilder();
            var ide             = vbeBuilder.Build().Object;
            var addin           = new Mock <IAddIn>().Object;
            var initialSettings = new GeneralSettings
            {
                EnableExperimentalFeatures = new List <ExperimentalFeatures>
                {
                    new ExperimentalFeatures()
                }
            };

            IWindsorContainer container = null;

            try
            {
                try
                {
                    container = new WindsorContainer().Install(new RubberduckIoCInstaller(ide, addin, initialSettings));
                }
                catch (Exception exception)
                {
                    Assert.Inconclusive($"Unable to register. {Environment.NewLine} {exception}");
                }

                var state = container.ResolveAll <RubberduckParserState>();

                //This test does not need an assert because it tests that no exception has been thrown.
            }
            finally
            {
                container?.Dispose();
            }
        }
        static void Main(string[] args)
        {
            //Load the test case.
            string boardString      = "E,E,J,H,E,T,J,T,E,E,H,J,T,H,E,E,J,H,E,T,J,T,E,E,H,J,T,H,J,E,E,J,H,E,T,J,T,E,E,H,J,T,E,H,E";
            string diceOutput       = "4,4,4,6,7,8,5,11,10,12,2,3,5,6,7,8,5,11,10,12,2,3,5,6,7,8,5,11,10,12";
            var    windsorContainer = new WindsorContainer();

            windsorContainer.Register(Component.For <IBank>().ImplementedBy <Bank>().LifestyleSingleton());
            windsorContainer.Register(Component.For <IPlayer>().ImplementedBy <Player>().LifestyleTransient());
            windsorContainer.Register(Component.For <EmptyCell>().ImplementedBy <EmptyCell>().LifestyleTransient());
            windsorContainer.Register(Component.For <JailCell>().ImplementedBy <JailCell>().LifestyleTransient());
            windsorContainer.Register(Component.For <TreasuryCell>().ImplementedBy <TreasuryCell>().LifestyleTransient());
            windsorContainer.Register(Component.For <HotelCell>().ImplementedBy <HotelCell>().LifestyleTransient());
            windsorContainer.Register(Component.For <BusinessHouseGame>().ImplementedBy <BusinessHouseGame>().LifestyleSingleton());
            var bank = windsorContainer.Resolve <IBank>(new Castle.MicroKernel.Arguments()
            {
                { "initialBalance", 5000 }
            });

            var businessHouseGame =
                windsorContainer.Resolve <BusinessHouseGame>(
                    new Castle.MicroKernel.Arguments()
            {
                { "container", windsorContainer }, { "bank", bank }, { "count", 3 }
            }
                    );

            var player1 = windsorContainer.Resolve <IPlayer>(new Castle.MicroKernel.Arguments()
            {
                { "initalBalance", 1000 }
            });
            var player2 = windsorContainer.Resolve <IPlayer>(new Castle.MicroKernel.Arguments()
            {
                { "initalBalance", 1000 }
            });
            var player3 = windsorContainer.Resolve <IPlayer>(new Castle.MicroKernel.Arguments()
            {
                { "initalBalance", 1000 }
            });

            Console.WriteLine(businessHouseGame.IsValidPlayers);
            businessHouseGame.BuildBoard(boardString);

            string[] diceOutputArray = diceOutput.Split(',');
            for (int index = 0; index < diceOutputArray.Length; index += 3)
            {
                businessHouseGame.Move(Convert.ToInt32(diceOutputArray[index]), player1);
                businessHouseGame.Move(Convert.ToInt32(diceOutputArray[index + 1]), player2);
                businessHouseGame.Move(Convert.ToInt32(diceOutputArray[index + 2]), player3);
            }

            Console.WriteLine("Player-1 has total money {0} and asset of amount : {1} = {2}", player1.Balance, player1.AssetBalance, player1.Balance + player1.AssetBalance);
            Console.WriteLine("Player-2 has total money {0} and asset of amount : {1} = {2}", player2.Balance, player2.AssetBalance, player2.Balance + player2.AssetBalance);
            Console.WriteLine("Player-3 has total money {0} and asset of amount : {1} = {2}", player3.Balance, player3.AssetBalance, player3.Balance + player3.AssetBalance);
            Console.WriteLine("Balance at Bank: {0}", bank.Balance);

            Console.ReadLine();
            windsorContainer.Dispose();
        }
Beispiel #38
0
 public void ContainerIsBeingDesposedProperly()
 {
     IWindsorContainer container = new WindsorContainer();
     InitializeWindsor(ref container);
     ILmsService service = container.Resolve<ILmsService>();
     container.Dispose();
     Assert.That(container.ResolveAll<Object>().Count(item => item != null) == 0);
 }
 internal static void Uninitialise()
 {
     if (_windsorContainer != null)
     {
         _windsorContainer.Dispose();
         _windsorContainer = null;
     }
 }
Beispiel #40
0
        public void Dispose()
        {
            var appHost = windsorContainer.Resolve <AppHost>();

            appHost.Stop();

            windsorContainer.Dispose();
        }
Beispiel #41
0
 public static void Main()
 {
     DependencyRegistration.Register();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
     WindsorContainer.Dispose();
 }
Beispiel #42
0
 static void Castle3()
 {
     var container = new WindsorContainer();
     container.Install(FromAssembly.This());
     var king = container.Resolve<IDateTimeProvider>();
     Console.WriteLine(king.Now);
     container.Dispose();
 }
 public void RegisterControllers_uses_lifestyle_transient()
 {
     var sut = new WindsorContainer();
     sut.Install(new WpfInstaller());
     sut.RegisterControllers(Assembly.GetAssembly(typeof(TerminalController)));
     Assert.AreNotSame(sut.Resolve(typeof (TerminalController)), sut.Resolve(typeof (TerminalController)));
     sut.Dispose();
 }
Beispiel #44
0
 public void Dispose()
 {
     if (_windsorContainer != null)
     {
         _windsorContainer.Resolve <NDistServer>().Stop();
         _windsorContainer.Dispose();
         _windsorContainer = null;
     }
 }
Beispiel #45
0
 private void button1_Click(object sender, EventArgs e)
 {
     IWindsorContainer container = new WindsorContainer();
     container.Install(Configuration.FromAppConfig());
     container.Install(FromAssembly.Named("com.Sconit.BatchJob.WindowsService"));
     IJobRunMgr jobRunMgr = container.Resolve<IJobRunMgr>();
     jobRunMgr.RunBatchJobs(container);
     container.Dispose();
 }
Beispiel #46
0
        public void ContainerIsBeingDesposedProperly()
        {
            IWindsorContainer container = new WindsorContainer();

            InitializeWindsor(ref container);
            container.Dispose();

            // Assert.That(container.ResolveAll<object>().Count(item => item != null) == 0);
        }
Beispiel #47
0
 /// <summary>
 /// Mains the specified args.
 /// </summary>
 /// <param name="args">The args.</param>
 public static void Main(string[] args)
 {
     IWindsorContainer container = new WindsorContainer().Install(FromAssembly.This());
     IOperation operation = container.Resolve<IOperation>();
     int i = operation.PerformOperation(1, 2);
     Console.WriteLine(string.Empty + i);
     Console.ReadLine();
     container.Dispose();
 }
Beispiel #48
0
        private static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Install(FromAssembly.This());

            DoWork(container);

            container.Dispose();
        }
Beispiel #49
0
 protected override void OnExit(ExitEventArgs e)
 {
     base.OnExit(e);
     if (container == null)
     {
         return;
     }
     container.Release(appInit);
     container.Dispose();
 }
Beispiel #50
0
 private void button1_Click(object sender, EventArgs e)
 {
     IWindsorContainer container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
     com.Sconit.Service.Dss.IOutboundMgr dssOutboundJob = container.Resolve<com.Sconit.Service.Dss.IOutboundMgr>("RctwoOutboundMgr.Service");
     com.Sconit.Service.Dss.IDssOutboundControlMgr dssOutboundControlMgr = container.Resolve<com.Sconit.Service.Dss.IDssOutboundControlMgr>("DssOutboundControlMgr.Service");
     DssOutboundControl dssOutboundControl = dssOutboundControlMgr.LoadDssOutboundControl(6);
     dssOutboundJob.ProcessOutbound(dssOutboundControl);
     //IJobRunMgr jobRunMgr = container.Resolve<IJobRunMgr>("JobRunMgr.service");
     //jobRunMgr.RunBatchJobs(container);
     container.Dispose();
 }
        public void AddAndResolveByService()
        {
            IContainer container = new WindsorContainer();
            container.MicroKernel.AddComponent("a", typeof (IService), typeof (DefaultService));

            object component = container.Resolve(typeof (IService));
            AssertNotNull(component);
            AssertNotNull(component as IService);

            container.Release(component);
            container.Dispose();
        }
Beispiel #52
0
        private static void Main(string[] args)
        {
            var container = new WindsorContainer(new XmlInterpreter());

            var magician = container.Resolve<IFantasyMagician>();

            Console.WriteLine("The magician's name is: {0}", magician.Name);

            container.Dispose();

            Console.ReadLine();
        }
Beispiel #53
0
        private static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Register(Component.For<IFantasyMagician>().ImplementedBy<Wizard>());

            var magician = container.Resolve<IFantasyMagician>();
            
            Console.WriteLine("The magician's name is: {0}", magician.Name);

            container.Dispose();
            
            Console.ReadLine();
        }
Beispiel #54
0
		public static void Main() 
		{
			IWindsorContainer container = 
				new WindsorContainer(
					new XmlInterpreter(
						new ConfigResource("castle")));
			
			MainForm mainForm = (MainForm) container[typeof(MainForm)];
			
			Application.Run(mainForm);
			
			container.Dispose();
		}
Beispiel #55
0
        private static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Register(Classes.FromThisAssembly().BasedOn<IRequireWindsor>().WithServiceAllInterfaces());

            var world = container.Resolve<IFantasyWorld>();

            Console.WriteLine("The center of the fantasy world is located at: \n{0}", world.WorldOrigin);

            container.Dispose();

            Console.ReadLine();
        }
Beispiel #56
0
        static void Main(string[] args)
        {
            Console.WriteLine("I'm the order processor");
            Log4NetLogger.Use("orderprocessor.log4net.xml");

            var container = new WindsorContainer();
            container.Register(
                Component.For(typeof(ISagaRepository<>))
                    .ImplementedBy(typeof(InMemorySagaRepository<>))
                    .LifeStyle.Singleton,
                Component.For<OrderSaga>(),
                Component.For<OrderService>()
                    .LifeStyle.Singleton,
                Component.For<IServiceBus>().UsingFactoryMethod(() =>
                {
                    return ServiceBusFactory.New(sbc =>
                    {
                        //sbc.ReceiveFrom("msmq://localhost/webdpc_responder");
                        sbc.ReceiveFrom("msmq://localhost/webdpc_orderprocessor");
                        sbc.UseMsmq();
                        sbc.UseMulticastSubscriptionClient();

                        sbc.UseControlBus();

                        sbc.Subscribe(subs => { subs.LoadFrom(container); });
                    });
                }).LifeStyle.Singleton);

            HostFactory.Run(c =>
            {
                c.SetServiceName("OrderProcessor");
                c.SetDisplayName("Order Processor");
                c.SetDescription("WebDPC order processor.");

                c.RunAsLocalSystem();
                c.DependsOnMsmq();

                DisplayStateMachine();

                c.Service<OrderService>(s =>
                {
                    s.ConstructUsing(builder => container.Resolve<OrderService>());
                    s.WhenStarted(o => o.Start());
                    s.WhenStopped(o =>
                    {
                        o.Stop();
                        container.Dispose();
                    });
                });
            });
        }
Beispiel #57
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //bootstrapping windsor
            var container = new WindsorContainer();
            container.Install(FromAssembly.This());
            var navController = container.Resolve<INavigationController>();

            Application.Run(navController.GetStartupWindow());

            container.Dispose();
        }
        public void AddAndResolveWithNestedContainerByService()
        {
            IContainer parent = new WindsorContainer();
            IContainer child = new WindsorContainer(parent);
            parent.MicroKernel.AddComponent("a", typeof (IService), typeof (DefaultService));

            object component = child.Resolve(typeof (IService));
            AssertNotNull(component);
            AssertNotNull(component as IService);

            child.Release(component);
            child.Dispose();
            parent.Dispose();
        }
        public void ResolvingTransientComponents_ReturnsDifferentInstanceEachTime()
        {
            IWindsorContainer container = new WindsorContainer();

            container.Register(
                Component.For<IRepository<Client>>().ImplementedBy<ClientRepository>().LifeStyle.Transient);

            var instanceA = container.Resolve<IRepository<Client>>();
            var instanceB = container.Resolve<IRepository<Client>>();

            Assert.AreNotSame(instanceA, instanceB);

            container.Dispose();
        }
Beispiel #60
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();

            container.Install(new HighFantasyInstaller());

            var magician = container.Resolve<IFantasyMagician>();

            Console.WriteLine("The magician's name is: {0}", magician.Name);

            container.Dispose();

            Console.ReadLine();
        }