Пример #1
0
        static void Main(string[] args)
        {
            IWindsorContainer container = new WindsorContainer();
            container.AddFacility<TypedFactoryFacility>();

            container.Register(Component.For<IDummyComponent>().ImplementedBy<DummyComponent>().Named("Action").LifeStyle.Transient);
            container.Register(Component.For<IDummyComponentFactory>().AsFactory().LifeStyle.Transient);

            IDummyComponentFactory factory = container.Resolve<IDummyComponentFactory>();

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("{0:N0} bytes used at the start", GC.GetTotalMemory(true));

                IDummyComponent[] array = new IDummyComponent[10];
                for (int j = 0; j < array.Length; j++)
                    array[j] = factory.GetAction();

                Console.WriteLine("{0:N0} bytes used at the mezivysledek", GC.GetTotalMemory(true));

                for (int j = 0; j < array.Length; j++)
                {
                    factory.Release(array[j]);
                    array[j] = null;
                }

                Console.WriteLine("{0:N0} bytes used at the end", GC.GetTotalMemory(true));
            }
        }
        public void Start()
        {
            WebApp.Start<StartupBootstrapper>(url);
            this.Info(() => "Started Keep-Alive Service");

            _server = new BackgroundJobServer();

            var container = new WindsorContainer();
            container.Register(Component.For<IApiClient>().ImplementedBy<ApiClient>());
            container.Register(Component.For<HealthCheck>());
            container.Register(Component.For<LoginCheck>());
            container.Register(Component.For<PackageCheck>());

            JobActivator.Current = new WindsorJobActivator(container.Kernel);

            RecurringJob.AddOrUpdate<HealthCheck>("DataPlatform HealthCheck", x => x.PingDataPlatform(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate<LoginCheck>("DataPlatform Mobile LoginCheck", x => x.MobileLogin(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate<LoginCheck>("DataPlatform API LoginCheck", x => x.ApiLogin(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate<PackageCheck>("DataPlatform API PackageCheck", x => x.InvokePackage(), ConfigurationManager.AppSettings["pollingCron"], TimeZoneInfo.Local);

            Console.WriteLine("\r");
            Console.WriteLine("Running on {0}", url);
            Console.WriteLine("\r\n");
            Console.WriteLine("*----------------------------------------------------------------------------*");
            Console.WriteLine("127.0.0.1 " + url + " <-- Required Hosts Entry!");
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("------------------------------------------------------------------------------");
            Console.WriteLine("\r");
            Console.WriteLine("Press Ctrl + c to exit");
        }
Пример #3
0
		public void given_two_configs_resolves_the_default_true_one_first_permutate()
		{
			var c = new WindsorContainer();
			c.Register(Component.For<INHibernateInstaller>().ImplementedBy<C2>());
			c.Register(Component.For<INHibernateInstaller>().ImplementedBy<C1>());
			AssertOrder(c);
		}
        private IWindsorContainer BuildContainerAndRegisterTypes()
        {
            var container = new WindsorContainer();
            container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();

            // register types from the config file
            IWindsorInstaller[] installers = new[]
                            {
                                Castle.Windsor.Installer.Configuration.FromXmlFile("app_config\\windsor\\components.config")
                            };

            container.Install(installers);

            // Register MVC controllers
            container.Register(Classes.FromAssemblyNamed("CustomController")
                                      .BasedOn<System.Web.Mvc.IController>()
                                      .LifestyleTransient());

            // Register WebApi controllers
            // http://forums.asp.net/t/1727621.aspx?Castle+Windsor+IOC+No+component+for+supporting+the+service+Web+Controllers+HomeController+was+found
            container.Register(Classes.FromAssemblyNamed("CustomController")
                                      .BasedOn<System.Web.Http.Controllers.IHttpController>()
                                      .LifestylePerWebRequest()
                                      .Configure(x => x.Named(x.Implementation.FullName)));

            return container;
        }
        protected override void Initialize(WindsorContainer container)
        {
            container.Register(Component.For<ITestService>().ImplementedBy<TestService>().Named("1"));
            container.Register(Component.For<ITestService>().ImplementedBy<TestService>().Named("2"));

            this.dependencyResolver = new WindsorDependencyResolver(container);
        }
Пример #6
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 void TestBasicOperations()
		{
			WindsorContainer container = new WindsorContainer(new DefaultConfigurationStore());

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

			container.Register(Component.For<ITransactionManager>().ImplementedBy<MockTransactionManager>().Named("transactionmanager"));

			container.Register(Component.For<CustomerService>().Named("services.customer"));

			CustomerService service = container.Resolve<CustomerService>("services.customer");

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

			MockTransactionManager transactionManager = container.Resolve<MockTransactionManager>("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
        public void RegisterContainer()
        {
            Container = new WindsorContainer();

            Container.Install(
                new ApplicationInstaller()
            );

            Container.Register(
                Component.For<IEventStorePresister>()
                         .ImplementedBy<TestEventStorePresister>()
                         .LifestyleTransient()
                );

            Container.Register(
                Component.For<IEventStoreLoader>()
                         .ImplementedBy<TestEventStoreLoader>()
                         .LifestyleTransient()
                );

            Container.Register(
                Component.For<TestEventStore>()
                );

            Container.Register(
                Component.For<IUnitOfWork, IEventStoreUnitOfWork>()
                .ImplementedBy<EventStoreUnitOfWork>()
                .LifestyleSingleton()
            );
        }
Пример #9
0
        protected void Application_Start()
        {
            /***Example of using Antler with Castle Windsor IoC container & Linq2Db ORM & SqlServer database. See connection string below***/

            /***! Plus we configure EntityFramework targeted on the same database,
                  just to use EF's functionallity to generate database & tables based on mappings(Linq2Db unable to do it) !***/

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new BlogViewEngine());

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            var container = new WindsorContainer();
            container.Register(Component.For<IBlogService>().ImplementedBy<Linq2DbBlogService>());
            container.Register(Classes.FromAssemblyNamed("Blog.Web.Common").BasedOn<BaseController>().LifestyleTransient());

            const string connectionString = "Data Source=(localdb)\\Projects;Initial Catalog=Antler;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
            AntlerConfigurator = new AntlerConfigurator();
            AntlerConfigurator.UseWindsorContainer(container)
                              .UseStorage(EntityFrameworkStorage.Use.WithConnectionString(connectionString).WithRecreatedDatabase(true).WithMappings(Assembly.Load("Blog.Mappings.EF")), "JustToGenerateStuff")
                              .UseStorage(Linq2DbStorage.Use(connectionString)).CreateInitialData(container.Resolve<IBlogService>());

            ControllerBuilder.Current.SetControllerFactory(new BlogControllerFactory(container.Resolve));
        }
Пример #10
0
        static void Main(string[] args)
        {
            WindsorContainer container = new WindsorContainer();
            container.Register(Component.For<Commerce>()); // first class needs to be registered as well
            container.Register(Component.For<IBillingProcessor>().ImplementedBy<BillingProcessor>());
            container.Register(Component.For<ICustomer>().ImplementedBy<Customer>());
            container.Register(Component.For<INotifier>().ImplementedBy<Notifier>());
            container.Register(Component.For<ILogger>().ImplementedBy<Logger>());

            Console.WriteLine("Castle Windsor DI Container Example");
            Console.WriteLine();

            OrderInfo orderInfo = new OrderInfo()
            {
                CustomerName = "Miguel Castro",
                Email = "*****@*****.**",
                Product = "Laptop",
                Price = 1200,
                CreditCard = "1234567890"
            };

            Console.WriteLine("Production:");
            Console.WriteLine();

            Commerce commerce = container.Resolve<Commerce>();
            commerce.ProcessOrder(orderInfo);

            Console.WriteLine();
            Console.WriteLine("Press [Enter] to exit...");
            Console.ReadLine();
        }
Пример #11
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();

            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}"
            );

            IWindsorContainer container = new WindsorContainer();

            container.Register(
                Classes
                    .FromThisAssembly()
                    .BasedOn<ApiController>()
                    .LifestyleScoped()
                );

            container.Register(
                Component.For<IBetDataAccess>().ImplementedBy<BetDataAccess>(),
                Component.For<IBetRiskCalculator>().ImplementedBy<BetRiskCalculator>(),
                Component.For<ICustomerRiskCalculator>().ImplementedBy<CustomerRiskCalculator>(),
                Component.For<IRiskService>().ImplementedBy<RiskService>()
                );

            config.DependencyResolver = new WindsorDependencyResolver(container.Kernel);
        }
Пример #12
0
        public static IWindsorContainer Build(string configPath)
        {
            var container = new WindsorContainer(new XmlInterpreter(configPath));

            // add array resolver
            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));

            // add facilities
            container.AddFacility(
                "logging.facility", 
                new LoggingFacility(LoggerImplementation.Log4net, "log4net.config"));

            // register handler selectors
            container.Kernel.AddHandlerSelector(new UrlBasedComponentSelector(
                                                    typeof(IBaseControllerService),
                                                    typeof(IImageFileService),
                                                    typeof(IConnectionStringProvider),
                                                    typeof(IEmailSender)
                                                    ));

            // automatically register controllers
            container.Register(AllTypes
                                   .Of<Controller>()
                                   .FromAssembly(Assembly.GetExecutingAssembly())
                                   .Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLower())));

            container.Register(
                Component.For<IDataContextProvider>().ImplementedBy<DataContextProvider>().LifeStyle.PerWebRequest,
                Component.For(typeof(IRepository<>)).ImplementedBy(typeof(Repository<>)).LifeStyle.Transient,
                Component.For(typeof(IRepository<Menu>)).ImplementedBy<MenuRepository>().LifeStyle.Transient,
                Component.For<IImageService>().ImplementedBy<ImageService>().Named("image.service").LifeStyle.Transient,
                Component.For<IEncryptionService>().ImplementedBy<EncryptionService>().Named("encryption.service").LifeStyle.Transient,
                Component.For<IHttpFileService>().ImplementedBy<HttpFileService>().LifeStyle.Transient,
                Component.For<ISizeService>().ImplementedBy<SizeService>().LifeStyle.Transient,
                Component.For<IUserService>().ImplementedBy<UserService>().LifeStyle.Transient,
                Component.For(typeof(IOrderableService<>)).ImplementedBy(typeof(OrderableService<>)).LifeStyle.Transient,
                Component.For<IPostageService>().ImplementedBy<PostageService>().LifeStyle.Transient,
                Component.For<IRepositoryResolver>().ImplementedBy<RepositoryResolver>().LifeStyle.Transient,
                Component.For<IHttpContextService>().ImplementedBy<HttpContextService>().LifeStyle.Transient,
                Component.For<IUnitOfWorkManager>().ImplementedBy<LinqToSqlUnitOfWorkManager>().LifeStyle.Transient,
                Component.For<IFormsAuthentication>().ImplementedBy<FormsAuthenticationWrapper>(),
                Component.For<IServiceLocator>().Instance(new WindsorServiceLocator(container)),
                Component.For<AuthenticateFilter>().LifeStyle.Transient,
                Component.For<UnitOfWorkFilter>().LifeStyle.Transient,
                Component.For<DataBinder>().LifeStyle.Transient,
                Component.For<LoadUsingFilter>().LifeStyle.Transient,
                Component.For<CurrentBasketBinder>().LifeStyle.Transient,
                Component.For<ProductBinder>().LifeStyle.Transient,
                Component.For<EnsureSsl>().LifeStyle.Transient,
                Component.For<OrderBinder>().LifeStyle.Transient,
				Component.For<MailingListSubscriptionBinder>().LifeStyle.Transient,
                Component.For<IOrderSearchService>().ImplementedBy<OrderSearchService>().LifeStyle.Transient,
                Component.For<IEmailBuilder>().ImplementedBy<EmailBuilder>().LifeStyle.Singleton,
                Component.For<IAppSettings>().ImplementedBy<AppSettings>().LifeStyle.Singleton,
                Component.For<IEmailService>().ImplementedBy<EmailService>().LifeStyle.Transient,
                Component.For<IDbConnectionChecker>().ImplementedBy<DbConnectionChecker>().LifeStyle.Transient
                );

            return container;
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            var container = new WindsorContainer();

            container.Register(
                AllTypes
                    .Pick().FromAssembly(typeof (ProductPresenter).Assembly)
                    .If(s => s.Name.EndsWith("Presenter"))
                    .WithService.FirstInterface()
                );

            container.Register(
                AllTypes
                    .Pick().FromAssembly(typeof (ProductService).Assembly)
                    .If(s => s.Name.EndsWith("Service"))
                    .WithService.FirstInterface()
                );

            container.Register(
                AllTypes
                    .Pick().FromAssembly(typeof (ProductRepository).Assembly)
                    .If(s => s.Name.EndsWith("Repository"))
                    .WithService.FirstInterface()
                );
            container.Register(Component.For<IDataContext>().ImplementedBy<MyOrmDataContext>());
            container.Register(Component.For<IProductView>().ImplementedBy<Default>());

            IoC.Init(container);
        }
Пример #14
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var windsor = new WindsorContainer();

            windsor.Register(
                Classes
                    .FromThisAssembly()
                    .Where(type => type.IsHandler() && type != typeof(MainForm))
                    .WithServiceAllHandlers()
                    .LifestyleTransient());

            windsor.Register(
                Component
                    .For<IDispatcher>()
                    .ImplementedBy<SynchronizationContextDispatcher<WindowsFormsSynchronizationContext>>()
                    .LifestyleSingleton(),
                Component
                    .For<MainForm>()
                    .LifestyleSingleton(),
                Component
                    .For<IHellowStrategy>()
                    .ImplementedBy<HellowStrategy>()
                    .LifestyleSingleton());
                
            windsor.AddFacility<PublisherFacility>();


            Application.Run(windsor.Resolve<MainForm>());
        }
Пример #15
0
        static void Main(string[] args)
        {
            IWindsorContainer container = new WindsorContainer();
            //container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

            container.Register(Component.For<IMyCollection>().ImplementedBy<MyColletion>().DependsOn(Property.ForKey("Value").Eq(5)).Named("a"));
            container.Register(Component.For<IMyCollection>().ImplementedBy<MyColletion>().DependsOn(Property.ForKey("Value").Eq(6)).Named("b"));
            container.Register(Component.For<IMyCollection>().ImplementedBy<MyColletion>().DependsOn(Property.ForKey("Value").Eq(7)).Named("c"));

            IList<IMyCollection> list = new List<IMyCollection>() { new MyColletion() {Value = 4}, new MyColletion() {Value = 5} };

            //container.Register(Component.For<IList<IMyCollection>>().ImplementedBy<List<IMyCollection>>().DependsOn(Property.ForKey<IList<IMyCollection>>().Is("a")).LifeStyle.Singleton);

            container.Register(Component.For<MyClass>().ServiceOverrides(new { list = new[] { "a", "b", "c" } }));
            //container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().DependsOn(new { list = new[] { "a", "b", "c" } }));
            //container.Register(Component.For<MyClass>().DependsOn(Property.ForKey("list").Is(new[] { "a", "b", "c" })));
            //container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().DependsOn(Property.ForKey<IList<IMyCollection>>).Is(new { list = new[] { "a", "b", "c" } })));

            //container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().DependsOn(Property.ForKey("list").Is("test")));
            //container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().DependsOn(Property.ForKey("list").Eq(list)));
            //container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
            //container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>());
            MyClass result = container.Resolve<MyClass>();
            //IMyInterface result = container.Resolve<IMyInterface>();
        }
Пример #16
0
		public void ReportsErrorsThrownByHostedServices()
		{
			var container = new WindsorContainer();

			container.Register(
				Component.For<IServiceHost>().Forward<MultitaskingServiceHost>().Instance(new MultitaskingServiceHost()));

			container.Register(
				Component.For<IHostedService>().Forward<FailingHostedService>().Instance(new FailingHostedService()));

			var runtime = new BasicFabric(container);

			var settings = new FabricRuntimeSettings();

			settings.ServiceHost.WithDefault(typeof(MultitaskingServiceHost));
			settings.HostedServices.WithDefault(new List<Type> { typeof(FailingHostedService) });

			runtime.Initialize(settings);

			runtime.Start();

			Assert.AreEqual(FabricRuntimeState.Started, runtime.State);

			Thread.Sleep(100); // let the exception have a chance to be thrown and caught

			var exceptions = runtime.GetExceptionsThrownByHostedServices();

			Assert.AreEqual(1, exceptions.Count);
		}
Пример #17
0
		public void ReportsBasicRuntimeStatistics()
		{
			var container = new WindsorContainer();

			container.Register(
				Component.For<IServiceHost>().Forward<MultitaskingServiceHost>().Instance(new MultitaskingServiceHost()));

			container.Register(Component.For<IHostedService>().Forward<FakeHostedService>().Instance(new FakeHostedService()));

			var runtime = new BasicFabric(container);

			var settings = new FabricRuntimeSettings();

			settings.ServiceHost.WithDefault(typeof(MultitaskingServiceHost));
			settings.HostedServices.WithDefault(new List<Type> { typeof(FakeHostedService) });

			runtime.Initialize(settings);

			runtime.Start();

			Assert.AreEqual(FabricRuntimeState.Started, runtime.State);
			Assert.AreEqual(FabricRuntimeState.Started, runtime.GetStatistics().RuntimeState);
			Assert.AreEqual(typeof(MultitaskingServiceHost), runtime.GetStatistics().ConfiguredServiceHost);
			Assert.AreEqual(typeof(FakeHostedService), runtime.GetStatistics().ConfiguredHostedServices[0]);
		}
Пример #18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            _container = new WindsorContainer();

            // auto register classes in LolStat dll
            _container.Register(Classes.FromAssemblyContaining<MainViewModel>()
                .IncludeNonPublicTypes()
                .InNamespace("LolStat", includeSubnamespaces: true)
                .WithService.DefaultInterfaces());

            // auto register classes in DataImporter dll
            _container.Register(Classes.FromAssemblyContaining<DataImporterClass>()
                .IncludeNonPublicTypes()
                .InNamespace("DataImporter", includeSubnamespaces: true)
                .WithService.DefaultInterfaces());

            // auto register classes in DataAccessLayer (DAL) dll
            _container.Register(Classes.FromAssemblyContaining<ContextFactory>()
                .IncludeNonPublicTypes()
                .InNamespace("DAL", includeSubnamespaces: true)
                .WithService.DefaultInterfaces());

            var mainWindow = _container.Resolve<IMainWindow>();
            mainWindow.Show();
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            IWindsorContainer container = new WindsorContainer();
            container.Register(Component.For<UserManager<CassandraUser>>().LifestylePerWebRequest());
            container.Register(
                Component.For<IUserStore<CassandraUser>>().ImplementedBy<CassandraUserStore<CassandraUser>>().LifestylePerWebRequest());

            container.Register(
                Component.For<Cluster>()
                    .UsingFactoryMethod(k => Cluster.Builder().AddContactPoint("127.0.0.1").Build())
                    .LifestylePerWebRequest(),

                Component.For<ISession>().UsingFactoryMethod(k => k.Resolve<Cluster>().Connect("windsorexample")).LifestylePerWebRequest()
            );

            container.Register(
                Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient()
            );

            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));
        }
Пример #20
0
        public IntegrationContainer()
        {
            container = new WindsorContainer();

            // allow collection injection
            container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

            // disable automatic property injection
            container.Kernel.ComponentModelBuilder.RemoveContributor(
                container.Kernel.ComponentModelBuilder.Contributors.OfType<PropertiesDependenciesModelInspector>().Single());

            container.Kernel.AddFacility<TypedFactoryFacility>();

            //selectively install Finance.Service classes
            container.Install(  new MappingsCreatorInstaller()
                                //new MappingsInstaller()
                                );

            //Persistence.EF installers
            container.Install(FromAssembly.Containing<ModelContextFactory>());

            //Core installers
            container.Install(FromAssembly.Containing<AppSettings>());

            //Integration inplememntations
            container.Register(Component.For<IConnection>().ImplementedBy<IntegrationConnection>());
            container.Register(Component.For<IExceptionService>().ImplementedBy<IntegrationExceptionService>());

            //Create all mappings
            container.Resolve<MappingsCreator>();

            DisplayRegistrations();
        }
		public void SetUp()
		{
			_Container = new WindsorContainer();
			_Container.AddFacility("autotx", new AutoTxFacility());
			_Container.Register(Component.For<ConcreteService>());
			_Container.Register(Component.For<ExtendedConcreteService>());
		}
		public void ContainerExtensions_overrideRegistration_should_override_a_previous_component()
		{
			var nss = new DelegateNamingSubSystem()
			{
				SubSystemHandler = ( s, hs ) =>
				{
					var containsOverridableServices = hs.Where( h => h.ComponentModel.IsOverridable() )
						.Any();

					if( containsOverridableServices && hs.Count() == 2 )
					{
						return hs.Single( h => !h.ComponentModel.IsOverridable() );
					}

					return null;
				}
			};

			var sut = new WindsorContainer();
			sut.Kernel.AddSubSystem( SubSystemConstants.NamingKey, nss );

			sut.Register( Component.For<IFoo>().ImplementedBy<AFoo>().Overridable() );
			sut.Register( Component.For<IFoo>().ImplementedBy<AnOtherFoo>() );

			var foo = sut.Resolve<IFoo>();
			foo.Should().Be.OfType<AnOtherFoo>();
		}
        public void ShouldResolveHandler()
        {
            var container = new WindsorContainer();
            container.AddFacility<TypedFactoryFacility>();

            container
                .Register(
                    Component
                        .For<IHandlerFactory>()
                        .AsFactory());

            container
                .Register(
                    Classes
                        .FromAssemblyContaining<RequestProcessor>()
                        .BasedOn(typeof(IHandler<,>))
                        .WithServiceAllInterfaces()
                        .LifestyleTransient());

            container.Register(Component.For<IMediator>().ImplementedBy<RequestProcessor>());

            var sut = container.Resolve<IMediator>();

            var response =
                sut.Send<CreateRetailerRequest, CreateRetailerResponse>(
                    new CreateRetailerRequest
                    {
                        Name = "Test Retailer",
                        Url = "www.testretailer.com"
                    });
        }
Пример #24
0
        protected virtual void AddRegistration(WindsorContainer container)
        {
            container.Register(Component.For<ISecurityAssertionProvider>().Instance(new SafeMethodOnlySecurityAssertionProvider()));
            // Use the version of the interceptor that doesn't allow any calls to go through
            // container.Register(Component.For<IInterceptor, ApplyViewPermissionsWithNoProceedInterceptor>());

            IoC.Initialize(container);
            container.Register(
                Component
                    .For(typeof(IMetricActionUrlAuthorizationProvider))
                    .Instance(metricActionUrlAuthService));

            container.Install(new TestConfigurationSpecificInstaller());
            container.Install(new SecurityComponentsInstaller(typeof(ApplyViewPermissionsByClaimWithNoProceedInterceptor)));
            container.Install(new MetricServiceInstaller());
            container.Install(new GenericServiceInstaller<Marker_EdFi_Dashboards_Warehouse_Resources>());
            container.Install(new GenericServiceInstaller<Marker_EdFi_Dashboards_Resources>());
            container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Data>());
            container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Metric_Data_Entities>());
            container.Install(new PersistedRepositoryInstaller<Marker_EdFi_Dashboards_Application_Data>());
            container.Install(new QueryInstaller<Marker_EdFi_Dashboards_Data>());
	        container.Install(new RepositoryInstaller<Marker_EdFi_Dashboards_Warehouse_Data>());

            container.Register(
                Classes.FromAssembly(securityAssembly)
                .BasedOn<IAuthorizationDelegate>()
                .WithService.FirstInterface(),
                Component.For<AuthorizationDelegateMap>());

            // Register the wrapped service locator singleton instance
            container.Register(
                Component.For<IServiceLocator>()
                    .Instance(IoC.WrappedServiceLocator));
        }
Пример #25
0
        public IBus Create()
        {
            var container = new WindsorContainer();
            container.Register(Component.For<ILogger>().ImplementedBy<ConsoleLogger>().LifestyleSingleton());
            container.RegisterNimbus(_typeProvider);

            container.Register(Component
                                   .For<IBus>()
                                   .ImplementedBy<Bus>()
                                   .UsingFactoryMethod<IBus>(() => new BusBuilder()
                                                                 .Configure()
                                                                 .WithConnectionString(_connectionString)
                                                                 .WithNames("TestApp", "TestInstance")
                                                                 .WithTypesFrom(_typeProvider)
                                                                 .WithWindsorDefaults(container)
                                                                 .WithDebugOptions(
                                                                     dc =>
                                                                         dc.RemoveAllExistingNamespaceElementsOnStartup(
                                                                             "I understand this will delete EVERYTHING in my namespace. I promise to only use this for test suites."))
                                                                 .Build())
                                   .OnCreate(b => ((Bus) b).Start())
                                   .LifestyleSingleton()
                );

            return container.Resolve<IBus>();
        }
        public void CanCreateDuplexProxyWithCallbackType()
        {
            IWindsorContainer localContainer = new WindsorContainer();

            localContainer.AddFacility<WcfFacility>();

            DuplexClientModel model = new DuplexClientModel
            {
                Endpoint = WcfEndpoint.ForContract<IServiceWithCallback>()
                    .BoundTo(new NetTcpBinding())
                    .At("net.tcp://localhost/ServiceWithCallback")
            }.WithCallback<ICallbackService>();

            localContainer.Register(WcfClient.ForChannels(model));

            localContainer.Register(Component.For<ICallbackService>()
                                        .ImplementedBy<CallbackService>());

            var callbackService = localContainer.Resolve<ICallbackService>();

            Assert.AreEqual(0, ((CallbackService)callbackService).ValueFromTheOtherSide);

            IServiceWithCallback proxy = localContainer.Resolve<IServiceWithCallback>();
            proxy.DoSomething(21);

            Assert.IsAssignableFrom(typeof(CallbackService), callbackService);
            Assert.AreEqual(42, ((CallbackService)callbackService).ValueFromTheOtherSide);
        }
        public WindsorControllerFactory()
        {
            _container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
            var controllerTypes =
                from t in Assembly.GetExecutingAssembly().GetTypes()
                where typeof(IController).IsAssignableFrom(t)
                select t;

            foreach (var t in controllerTypes)
            {
                _container.Register(Component.For(t).Named(t.FullName).LifeStyle.PerWebRequest);
            }

            // Add HttpContext
            _container.Register(Component.For<HttpRequestBase>()
                                    .LifeStyle.PerWebRequest
                                    .UsingFactoryMethod(() => new HttpRequestWrapper(HttpContext.Current.Request)));

            _container.Register(Component.For<HttpContextBase>()
                                    .LifeStyle.PerWebRequest
                                    .UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));

            _container.Register(Component.For<IDocumentStore>()
                                    .LifeStyle.Singleton
                                    .UsingFactoryMethod(RavenFactory.GetDocumentStore));

            _container.Register(Component.For<IDocumentSession>()
                .LifeStyle.PerWebRequest
                .UsingFactoryMethod(RavenFactory.GetSession));
        }
Пример #28
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            ModelBinders.Binders.Add(typeof(Book), new BookDataBinder());

            var container = new WindsorContainer();
            container.Register(
                Classes.FromAssemblyContaining<HomeController>()
                .BasedOn<Controller>().LifestyleTransient());

            container.Register(
                Component.For<BooksContext>().LifestylePerWebRequest(),
                Component.For<IUnitOfWork<BooksContext>>().ImplementedBy<UnitOfWork>().LifestylePerWebRequest(),
                Component.For<IAuthorRepository>().ImplementedBy<AuthorRepository>().LifestylePerWebRequest(),
                Component.For<ICategoryRepository>().ImplementedBy<CategoryRepository>().LifestylePerWebRequest(),
                Component.For<IReadingsRepository>().ImplementedBy<ReadingsRepository>().LifestylePerWebRequest(),
                Component.For<IBooksRepository>().ImplementedBy<BooksRepository>().LifestylePerWebRequest(),
                Component.For<IStatisticsRepository>().ImplementedBy<StatisticsRepository>().LifestylePerWebRequest(),
                Component.For<IBookBadgeRepository>().ImplementedBy<BookBadgeRepository>().LifestylePerWebRequest()
                );


            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));
        }
Пример #29
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Register(Component.For<PaymentService>());

            var myBossMasterCard = new MasterCard("My boss's name", "123456789-123");

            // INSTANCE, resolve against this instance, all the time
            container.Register(Component.For<ICard>().Instance(myBossMasterCard));

            // NORMAL register
            //container.Register(Component.For<ICard>().ImplementedBy<VisaCard>());

            // NAMED register
            container.Register(Component.For<ICard>().ImplementedBy<VisaCard>().Named("myCard"));
            container.Register(Component.For<ICard>().ImplementedBy<AmericanExpress>().Named("wifesCard"));

            var creditCard = container.Resolve<ICard>();

            var myCard = container.Resolve<ICard>("myCard");

            // LIFECYCLE:  SINGLETON, TRANSIENT
            var wifesCard = container.Resolve<ICard>("wifesCard");
            var mistressCard = container.Resolve<ICard>("wifesCard");

            var allCards = container.ResolveAll<ICard>();

            var paymentService = container.Resolve<PaymentService>();

            //LIFECYCLE, default singleton, unity is default transient aka new object
            // container.Register(Component.For<ICard>().LifeStyle.Transient.ImplementedBy<AmericanExpress>().Named("wifesCard"));
        }
        protected override void EstablishContext()
        {
            idCodeService = mocks.Stub<IIdCodeService>();
            httpRequestProvider = mocks.Stub<IHttpRequestProvider>();
            httpContextItemsProvider = mocks.Stub<IHttpContextItemsProvider>();
            requestUrlBaseProvider = mocks.Stub<IRequestUrlBaseProvider>();

            var containerMock = new WindsorContainer();

            containerMock.Register(Component.For<IIdCodeService>().Instance(idCodeService));
            containerMock.Register(Component.For<IHttpRequestProvider>().Instance(httpRequestProvider));
            containerMock.Register(Component.For<IHttpContextItemsProvider>().Instance(httpContextItemsProvider));
            containerMock.Register(Component.For<IRequestUrlBaseProvider>().Instance(requestUrlBaseProvider));

            var chainTypes = new List<Type>()
            {
                typeof(HttpContextItemsLeaCodeProvider),
                typeof(DashboardContextLeaCodeProvider),
                typeof(HttpRequestUrlLeaCodeProvider)
            };
            
            var chainRegistrar = new ChainOfResponsibilityRegistrar(containerMock);
            chainRegistrar.RegisterChainOf<ILocalEducationAgencyContextProvider, NullLeaCodeProvider>(chainTypes.ToArray());

            IoC.Initialize(containerMock);
        }
        public void Interceptor_selected_by_selector_gets_released_properly()
        {
            DisposableInterceptor.InstancesDisposed = 0;
            DisposableInterceptor.InstancesCreated  = 0;
            var container = new WindsorContainer();

            container.Kernel.ProxyFactory.AddInterceptorSelector(new ByTypeInterceptorSelector(typeof(DisposableInterceptor)));
            container.Register(Component.For <DisposableInterceptor>(),
                               Component.For <A>().LifeStyle.Transient);

            var a = container.Resolve <A>();

            Assert.AreEqual(1, DisposableInterceptor.InstancesCreated);

            container.Release(a);
            Assert.AreEqual(1, DisposableInterceptor.InstancesDisposed);
        }
Пример #32
0
        protected override void Configure()
        {
            _container = new WindsorContainer();
            _container.Register(
                Component.For <IEventAggregator>()
                .ImplementedBy <EventAggregator>()
                .LifestyleSingleton(),
                Component.For <IDialogService>()
                .ImplementedBy <DialogService>()
                .LifestyleSingleton(),
                Component.For <IWindowManager>()
                .ImplementedBy <WindowManager>()
                .LifestyleSingleton()
                );

            RegisterViewModels();
        }
        public HttpResponseMessage Get_all_children(int id)
        {
            var container = new WindsorContainer();

            container.Register(Component.For <ICompanyHierarchy>().ImplementedBy <CompanyHierarchy>().LifestyleSingleton());

            // Resolve an object of type ICompanyHierarchy (ask the container for an instance)
            // This is analagous to calling new() in a non-IoC application.
            _CompanyHierarchy = container.Resolve <ICompanyHierarchy>();

            Common.Models.Node node = _CompanyHierarchy.Getnode(id);

            IEnumerable <Common.Models.Node> resultsnodes = _CompanyHierarchy.Get_all_children(node);


            return(Share.Json <Common.Models.Node>(resultsnodes));
        }
Пример #34
0
        private ServiceHost createServiceHost()
        {
            WindsorContainer container = new WindsorContainer();

            container.AddFacility <WcfFacility>();
            container.Register(
                Component.For <WebService>().
                DependsOn(Dependency.OnValue("contentSubPath", contentPath))
                .DependsOn(Dependency.OnValue("errorPageTemplatePath", errorPagePath))
                );
            DefaultServiceHostFactory castleWindsorFactory =
                new DefaultServiceHostFactory(container.Kernel);
            var windsorServiceHost = (ServiceHost)castleWindsorFactory.
                                     CreateServiceHost(typeof(WebService).AssemblyQualifiedName, new Uri[] { });

            return(windsorServiceHost);
        }
Пример #35
0
        static void Main()
        {
            var container    = new WindsorContainer();
            var rootSelector = new CustomScopeRootSelector(typeof(Root1), typeof(Root2));

            container.Register(
                Component.For <Root1>().LifestyleTransient(),
                Component.For <Root2>().LifestyleTransient(),
                Component.For <Dep1>().LifestyleBoundTo(rootSelector.Selector),
                Component.For <Dep2>().LifestyleBoundTo(rootSelector.Selector)
                );
            var r1 = container.Resolve <Root1>();
            var r2 = container.Resolve <Root2>();

            Debug.Assert(r1.D1 == r1.D2);
            Debug.Assert(r1.D1 != r2.D1);
        }
        public void SetUp()
        {
            var mockRepository   = new Mock <IRepositoryWithTypedId <Employee, int> >();
            var windsorContainer = new WindsorContainer();

            mockRepository.Setup(r => r.Get(It.IsAny <int>())).Returns((int newId) => new Employee(newId));

            windsorContainer.Register(
                Component
                .For <IRepositoryWithTypedId <Employee, int> >()
                .Instance(mockRepository.Object));


            var dependencyResolver = new WindsorDependencyResolver(windsorContainer);

            DependencyResolver.SetResolver(dependencyResolver);
        }
        static IWindsorContainer CreateContainer()
        {
            IWindsorContainer container = new WindsorContainer();

            // Add support for injection of arrays and IList<T> into
            // the components
            var kernel = container.Kernel;

            kernel.Resolver.AddSubResolver(new ArrayResolver(kernel));
            kernel.Resolver.AddSubResolver(new ListResolver(kernel));

            // Register the components into the container
            container.Register(Component.For <IBroadcastService>().ImplementedBy <BroadcastService>());

            ContainerManager.SetContainerProvider(() => new WindsorObjectBuilder(container));
            return(container);
        }
Пример #38
0
        private static WindsorContainer CreateContainer(Assembly applicationAssembly)
        {
            var container = new WindsorContainer();

            container.AddFacility <TypedFactoryFacility>();

            container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, allowEmptyArray: true));
            container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, allowEmptyCollections: true));

            container.Kernel.ComponentModelBuilder.AddContributor(new PhoneClientComponentModelContributor());

            container.Register(Component.For <IWindsorContainer>().Instance(container));

            container.Install(FromAssembly.Instance(applicationAssembly));

            return(container);
        }
Пример #39
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);
            Console.WriteLine();



            container.Dispose();

            Console.ReadLine();
        }
Пример #40
0
        static void Main(string[] args)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo("client.log4net.xml"));
            _log.Info("Client Loading");

            WindsorContainer container;

            RunConfiguration cfg = RunnerConfigurator.New(c =>
            {
                c.SetServiceName("SampleClientService");
                c.SetDisplayName("SampleClientService");
                c.SetDescription("SampleClientService");

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

                c.ConfigureService <ClientService>(s =>
                {
                    string serviceName = typeof(ClientService).Name;

                    s.Named(serviceName);
                    s.WhenStarted(o =>
                    {
                        container = new WindsorContainer();

                        container.Register(Component.For <PasswordUpdater>());

                        Bus.Initialize(sbc =>
                        {
                            sbc.ReceiveFrom("msmq://localhost/mt_client");
                            sbc.UseSubscriptionService("msmq://localhost/mt_subscriptions");
                            sbc.UseMsmq();
                            sbc.VerifyMsDtcConfiguration();
                            sbc.VerifyMsmqConfiguration();
                        });
                        var bus = Bus.Instance;
                        o.Start(bus);
                    });
                    s.WhenStopped(o => o.Stop());

                    s.HowToBuildService(name => new ClientService());
                });
            });

            Runner.Host(cfg, args);
        }
Пример #41
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            var container = new WindsorContainer();

            container.Install(new DALInstaller());
            container.Install(new BLInstaller());

            container.Register(
                Classes.FromThisAssembly().BasedOn(typeof(ViewModelBase)).WithServiceSelf().LifestyleTransient(),
                Classes.FromThisAssembly().BasedOn(typeof(Window)).WithServiceSelf().LifestyleTransient(),
                Classes.FromThisAssembly().BasedOn(typeof(ICommand)).WithServiceSelf().LifestyleTransient()
                );

            var mainWindow = container.Resolve <MainWindow>();

            mainWindow.Show();
        }
Пример #42
0
        public void SubDependencyResolverHasHigherPriorityThanHandlerSelector()
        {
            IWindsorContainer container = new WindsorContainer();

            container.Register(Component.For(typeof(Person)).LifeStyle.Is(LifestyleType.Transient)).Register(
                Component.For <IWatcher>().ImplementedBy <BirdWatcher>().Named("bird.watcher")).Register(
                Component.For <IWatcher>().ImplementedBy <SatiWatcher>().Named("astronomy.watcher"));
            var selector = new WatcherSelector();

            container.Kernel.AddHandlerSelector(selector);
            container.Kernel.Resolver.AddSubResolver(new WatchSubDependencySelector());

            selector.Interest = Interest.Biology;
            Assert.IsInstanceOf(typeof(SatiWatcher), container.Resolve <Person>().Watcher,
                                "sub dependency should resolve sati");
            Assert.IsInstanceOf(typeof(BirdWatcher), container.Resolve <IWatcher>(), "root dependency should resolve bird");
        }
        public void Context()
        {
            _windsorContainer = new WindsorContainer();

            _windsorContainer.Register(
                Component.For <IServiceType>()
                .ImplementedBy <ServiceTypeOne>()
                .LifeStyle.Transient,
                Component.For <IServiceType>()
                .ImplementedBy <ServiceTypeTwo>()
                .LifeStyle.Transient
                );

            var castleContainer = new CastleContainer(_windsorContainer);

            _result = castleContainer.ResolveAll <IServiceType>();
        }
Пример #44
0
        /// <summary>
        /// 拦截器
        /// 1:获取一个容器
        /// 2:在容器中注册接口和类,并且把需要拦截的类,添加拦截器
        /// 3:容器的核心对象的组件注册委托中添加拦截器注入,
        ///    即IHandler对象的ComponentModel属性的拦截器列表中添加需要注入的拦截器
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //IWindsorContainer container1 = new WindsorContainer(new XmlInterpreter());
            //IBllDealOrder bllOrder = container1.Resolve<IBllDealOrder>();
            //Console.WriteLine(bllOrder.Deal("jackychen"));
            //Console.Read();

            //IWindsorContainer container1 = new WindsorContainer(new XmlInterpreter());
            IWindsorContainer container1 = new WindsorContainer();

            container1.Register(new RegistInterface());
            InterceptorRegistrar.Initialize(container1);
            IBllGetOrder bllOrder = container1.Resolve <IBllGetOrder>();

            Console.WriteLine(bllOrder.Get("jackychen"));
            Console.Read();
        }
Пример #45
0
        public void SelectUsingBusinessLogic_SubDependency()
        {
            IWindsorContainer container = new WindsorContainer();

            container.Register(Component.For(typeof(Person)).LifeStyle.Is(LifestyleType.Transient)).Register(
                Component.For <IWatcher>().ImplementedBy <BirdWatcher>().Named("bird.watcher")).Register(
                Component.For <IWatcher>().ImplementedBy <SatiWatcher>().Named("astronomy.watcher"));
            var selector = new WatcherSelector();

            container.Kernel.AddHandlerSelector(selector);

            Assert.IsInstanceOf(typeof(BirdWatcher), container.Resolve <Person>().Watcher, "default");
            selector.Interest = Interest.Astronomy;
            Assert.IsInstanceOf(typeof(SatiWatcher), container.Resolve <Person>().Watcher, "change-by-context");
            selector.Interest = Interest.Biology;
            Assert.IsInstanceOf(typeof(BirdWatcher), container.Resolve <Person>().Watcher, "explicit");
        }
Пример #46
0
        public void RegisterAllSauces()
        {
            var container = new WindsorContainer();

            container.Register(AllTypes
                               .FromAssemblyContaining <SauceBéarnaise>()
                               .Where(t => t.Name.StartsWith("Sauce"))
                               .WithService.AllInterfaces());

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

            Assert.True(sauces.OfType <SauceBéarnaise>().Any());
            Assert.True(sauces.OfType <SauceHollandaise>().Any());
            Assert.True(sauces.OfType <SauceMousseline>().Any());

            Assert.False(sauces.OfType <Steak>().Any());
        }
Пример #47
0
        static void Main(string[] args)
        {
            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);

            _containerClient = new WindsorContainer(new XmlInterpreter("config_client.config"));

            _containerClient.Register(Component.For <IRemoteServ1>());

            Console.WriteLine("Started. Initial request...");

            // Do initial request to see if path is clear


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

            InvokeBatch(service);


            Console.WriteLine("Performing firehose requests");

            for (var i = 0; i < 40; i++)
            {
                var t = new Thread(TestRemoteService)
                {
                    IsBackground = true
                };
                t.Start();
            }

            // Release the horses
            _proceedEvent.Set();

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                _stopping = true;

                Thread.Sleep(1000);

                _containerClient.Dispose();
            };

            Thread.CurrentThread.Join();
        }
Пример #48
0
 public void GlobalJobListeners()
 {
     using (var c = new WindsorContainer()) {
         var config = new MutableConfiguration("facility");
         config.CreateChild("quartz").CreateChild("item", "qwe").Attribute("key", "qq");
         config.CreateChild("globalJobListeners").CreateChild("item", "${jobli}");
         c.Kernel.ConfigurationStore.AddFacilityConfiguration("quartz", config);
         c.Register(Component.For <IJobListener>().ImplementedBy <SomeJobListener>().Named("jobli"));
         c.AddFacility("quartz", new QuartzFacility());
         var scheduler = (QuartzNetScheduler)c.Resolve <IScheduler>();
         foreach (IJobListener l in scheduler.ListenerManager.GetJobListeners())
         {
             Console.WriteLine(l.Name);
         }
         Assert.AreEqual(2, scheduler.ListenerManager.GetJobListeners().Count);
     }
 }
Пример #49
0
        protected IWindsorContainer InitWindsorContainer(
            IRepositories repositories,
            IRetrievers retrievers,
            RoleManager <ApplicationRole> roleManager)
        {
            var windsorContainer = new WindsorContainer();

            windsorContainer.Register(
                Component.For <IServices>()
                .ImplementedBy <Blog.Services.Services>()
                .DependsOn(Dependency.OnValue("repositories", repositories))
                .DependsOn(Dependency.OnValue("retrievers", retrievers))
                .DependsOn(Dependency.OnValue("roleManager", roleManager))
                );

            return(windsorContainer);
        }
Пример #50
0
        public void SetUp()
        {
            _handler      = MockRepository.GenerateStub <ICommandExecutor <FakeCommand> >();
            _container    = new WindsorContainer();
            _interceptor  = new FakeInterceptor();
            _interceptor2 = new FakeInterceptor2();
            _container.Register(
                Component.For <IWindsorContainer>().Instance(_container),
                Component.For <ICommandExecutor <FakeCommand> >().Instance(_handler),
                Component.For <ICommandServiceInterceptor>().Instance(_interceptor),
                Component.For <ICommandServiceInterceptor>().Instance(_interceptor2),
                Component.For <ICommandService>().ImplementedBy <WindsorCommandService>());
            var svc = _container.Resolve <ICommandService>();

            _testCommand = new FakeCommand();
            svc.Execute(_testCommand);
        }
Пример #51
0
        public static IWindsorContainer Build(HttpConfiguration config)
        {
            // Install-Package Castle.Windsor
            // Install-Package Castle.LoggingFacility
            var container = new WindsorContainer();;

            // register the common assembly
            RegisterAllDefaultInterfaces(container, "WeatherLab.Model");

            // register API
            container.Register(Classes.FromThisAssembly().BasedOn <IHttpController>().LifestyleTransient());
            config.Services.Replace(typeof(IHttpControllerActivator), new WindsorControllerActivator(container));

            container.Install(FromAssembly.This());

            return(container);
        }
        public void SetUp()
        {
            _testEvent = new FakeEvent();
            _handler1  = MockRepository.GenerateMock <IEventHandler <FakeEvent> >();
            _handler2  = MockRepository.GenerateMock <IEventHandler <SourcedEvent> >();
            _handler3  = MockRepository.GenerateMock <IEventHandler <IEvent> >();
            _container = new WindsorContainer();
            _container.Register(
                Component.For <IWindsorContainer>().Instance(_container),
                Component.For <IEventHandler <FakeEvent> >().Instance(_handler1),
                Component.For <IEventHandler <SourcedEvent> >().Instance(_handler2),
                Component.For <IEventHandler <IEvent> >().Instance(_handler3),
                Component.For <IEventBus>().ImplementedBy <WindsorInProcessEventBus>());
            var svc = _container.Resolve <IEventBus>();

            svc.Publish(_testEvent);
        }
Пример #53
0
        public void Cannot_Register_Class_Without_Virtual_Method()
        {
            var c = new WindsorContainer();

            c.AddFacility <AutoTxFacility>();

            try
            {
                c.Register(Component.For <FaultyComponent>());
                Assert.Fail("invalid component registration should be noted.");
            }
            catch (FacilityException ex)
            {
                Assert.That(ex.Message.Contains("FaultyMethod"));
                Assert.That(ex.Message.Contains("virtual"));
            }
        }
Пример #54
0
 public void CommandsHandlerWiringTest()
 {
     using (var container = new WindsorContainer())
     {
         container
         .Register(Component.For <ILogFactory>().Instance(_logFactory))
         .Register(Component.For <IMessagingEngine>().Instance(new Mock <IMessagingEngine>().Object))
         .AddFacility <CqrsFacility>(f => f.RunInMemory().Contexts(Register.BoundedContext("bc")))
         .Register(Component.For <CommandsHandler>().AsCommandsHandler("bc").LifestyleSingleton())
         .Resolve <ICqrsEngineBootstrapper>().Start();
         var cqrsEngine      = (CqrsEngine)container.Resolve <ICqrsEngine>();
         var commandsHandler = container.Resolve <CommandsHandler>();
         cqrsEngine.Contexts.First(c => c.Name == "bc").CommandDispatcher.Dispatch("test", (delay, acknowledge) => { }, new Endpoint(), "route");
         Thread.Sleep(1300);
         Assert.That(commandsHandler.HandledCommands, Is.EqualTo(new[] { "test" }), "Command was not dispatched");
     }
 }
Пример #55
0
        public void it_should_add_custom_header_to_headers_collection_using_interface()
        {
            using (var container = new WindsorContainer("RhinoQueues/RhinoQueues.config"))
            {
                container.AddFacility("rhino.esb", new RhinoServiceBusFacility());
                container.Register(Component.For <ICustomizeMessageHeaders>().ImplementedBy <AppIdentityCustomizer>().LifeStyle.Is(LifestyleType.Transient));

                var builder = container.Resolve <IMessageBuilder <MessagePayload> >();
                builder.Initialize(new Endpoint {
                    Uri = RhinoQueuesOneWayBus.NullEndpoint
                });
                var msg = builder.BuildFromMessageBatch("somemsg");
                Assert.NotNull(msg);
                Assert.NotEqual(0, msg.Data.Length);
                Assert.Equal("mikey", msg.Headers["user-id"]);
            }
        }
        private IWindsorContainer CreateContainer()
        {
            var container = new WindsorContainer();

            container.Register(Component.For <IWindsorContainer>().Instance(container).LifeStyle.Singleton);
            container.Register(Component.For <QueryModelInspector>().ImplementedBy <QueryModelInspector>());
            container.Register(Component.For <IDataProvider>().ImplementedBy <TestDataProvider>());
            container.Register(Component.For <IFilterLocator>().ImplementedBy <FilterLocator>());
            container.Register(Component.For(typeof(IRepository <>)).ImplementedBy(typeof(FakeRepository <>)));
            container.Register(AllTypes.FromAssemblyContaining <InStockProductsFilter>().BasedOn(typeof(IFilter <>)));
            return(container);
        }
Пример #57
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            container = new WindsorContainer();
            container.Register(Component.For <FirstViewModel>());
            container.Register(Component.For <SecondViewModel>());
            container.Register(Component.For <ThirdViewModel>());
            container.Register(Component.For <MainWindowViewModel>());
            container.Register(Component.For <MainWindow>());

            container.Register(Component.For <EditTitleDialogViewModel>());
            container.Register(Component.For <IEditTitleDialogFactory>().ImplementedBy <EditTitleDialogFactory>());

            container.Register(Component.For <IMessageBoxService>().ImplementedBy <MessageBoxService>());

            var mainWindow = container.Resolve <MainWindow>();

            mainWindow.ShowDialog();
        }
        public async Task Should_Log_Exceptions()
        {
            var _configuration = new HttpConfiguration();
            var messages       = new List <string>();
            var logger         = MockRepository.GenerateMock <ILogger>();

            logger
            .Expect(x => x.Error(Arg <string> .Is.TypeOf, Arg <Exception> .Is.TypeOf))
            .WhenCalled(m =>
            {
                messages.Add((string)m.Arguments[0]);
            });

            var _container = new WindsorContainer();

            _container.Register(
                Component.For <ILogger>().Instance(logger)
                );
            _container.Install(FromAssembly.This(),
                               new MediatRInstaller(Classes.FromThisAssembly()),
                               new WebApiInstaller(_configuration, Classes.FromThisAssembly())
                               .UseScopeAccessor <LifetimeScopeAccessor>()
                               .UseDefaultRoutesAndAttributeRoutes()
                               .TypeNameHandling()
                               .IgnoreNulls()
                               .UseGlobalExceptionLogging()
                               );

            var mediator = _container.Resolve <IMediator>();

            using (WebApp.Start(BaseAddress, builder => builder.UseWebApi(_configuration)))
            {
                try
                {
                    await mediator.At(BaseAddress)
                    .GetAsync <string>($"{BaseAddress}throwException");
                }
                catch (Exception)
                {
                    Assert.AreEqual(1, messages.Count);
                }
            }

            _container.Dispose();
        }
Пример #59
0
        // we would pass in a configuration class that contains the maximumNumberOfCommands and other config settings

        public static IWindsorContainer Create(int maximumNumberOfCommands)
        {
            var container = new WindsorContainer();

            container.Register(Component.For <IWindsorContainer>().Instance(container).LifestyleSingleton());
            container.Register(Component.For <IPlanet>().ImplementedBy <Mars>().LifestyleTransient());
            container.Register(Component.For <ICompass>().ImplementedBy <Compass>().LifestyleTransient());
            container.Register(Component.For <ICoordinates>().ImplementedBy <Coordinates>().LifestyleTransient());
            container.Register(Component.For <INavigation>().ImplementedBy <Navigation>().LifestyleTransient()
                               .DependsOn(Dependency.OnValue <CardinalHeading>(CardinalHeading.South)));
            container.Register(Component.For <IRover>().ImplementedBy <Core.MarsRover>().LifestyleTransient());
            container.Register(Component.For <MarsRoverController>().ImplementedBy <Core.MarsRoverController>().LifestyleTransient()
                               .DependsOn(Dependency.OnValue <int>(maximumNumberOfCommands)));

            return(container);
        }
Пример #60
0
        protected AbstractV2ProjectionEngineTests(String pollingClientVersion = "1")
        {
            TestHelper.RegisterSerializerForFlatId <SampleAggregateId>();
            _container = new WindsorContainer();
            _container.AddFacility <TypedFactoryFacility>();

            _container.AddFacility <LoggingFacility>(f =>
                                                     f.LogUsing(LoggerImplementation.Null));

            _container.Resolve <ILoggerFactory>();

            _container.Register(
                Component
                .For <ICommitPollingClient>()
                .ImplementedBy <CommitPollingClient2>()
                .LifestyleTransient(),
                Component
                .For <ICommitPollingClientFactory>()
                .AsFactory(),
                Component
                .For <ICommitEnhancer>()
                .UsingFactoryMethod(() => new CommitEnhancer()),
                Component
                .For <INStoreLoggerFactory>()
                .ImplementedBy <NStoreCastleLoggerFactory>(),
                Component
                .For <ILoggerThreadContextManager>()
                .ImplementedBy <NullLoggerThreadContextManager>(),
                Component
                .For <ILogger>()
                .Instance(NullLogger.Instance));

            switch (pollingClientVersion)
            {
            case "1":
                throw new NotSupportedException("Version 1 of projection engine was removed due to migration to NES6");

            case "2":
                _pollingClientFactory = _container.Resolve <ICommitPollingClientFactory>();
                break;

            default:
                throw new NotSupportedException("Version not supported");
            }
        }