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 (); }
private WindsorContainer CreateContainer() { var container = new WindsorContainer(new XmlInterpreter()); var facility = new RhinoServiceBusFacility().UseFlatQueueStructure(); container.Kernel.AddFacility("rhino.esb", facility); return container; }
public void Init() { container = new WindsorContainer(); store = (IConfigurationStore) container.Kernel.GetSubSystem(SubSystemConstants.ConfigurationStoreKey); }
public void CanRegisterSimpleService() { var c = new WindsorContainer(); c.Register(Component.For<IDependency>().ImplementedBy<DependencyA>()); Assert.That(c.Resolve<IDependency>(), Is.InstanceOf<DependencyA>()); }
static IWindsorContainer ConfigureIoC() { var container = new WindsorContainer(); container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true)); container.Install(Configuration.FromAppConfig(), FromAssembly.This(), FromAssembly.Containing<GuestBookXmlProvider>()); return container; }
public static void Main(string[] args) { var container = new WindsorContainer (); container.Install (new ServicesInstaller ()); container.Resolve<DemoApp> ().Run (); }
public void TestBasicOperations() { WindsorContainer container = new WindsorContainer(new DefaultConfigurationStore()); container.AddFacility("transactionmanagement", new TransactionFacility()); container.AddComponent("transactionmanager", typeof(ITransactionManager), typeof(MockTransactionManager)); container.AddComponent("services.customer", typeof(CustomerService)); CustomerService service = (CustomerService)container["services.customer"]; service.Insert("TestCustomer", "Rua P Leite, 33"); MockTransactionManager transactionManager = (MockTransactionManager) container["transactionmanager"]; Assert.AreEqual(1, transactionManager.TransactionCount); Assert.AreEqual(1, transactionManager.CommittedCount); Assert.AreEqual(0, transactionManager.RolledBackCount); try { service.Delete(1); } catch (Exception) { // Expected } Assert.AreEqual(2, transactionManager.TransactionCount); Assert.AreEqual(1, transactionManager.CommittedCount); Assert.AreEqual(1, transactionManager.RolledBackCount); }
public void AddingToTwoParentContainsThrowsKernelException() { IWindsorContainer container3 = new WindsorContainer(); IWindsorContainer childcontainer = new WindsorContainer(); Container.AddChildContainer(childcontainer); container3.AddChildContainer(childcontainer); }
// Models singleton over transient instance models static void Main(string[] args) { IWindsorContainer container = new WindsorContainer(new XmlInterpreter("windsor.config")); //IWindsorContainer container = CreateContainer(); IBar bar = container.Resolve<IBar>(); if (bar != null) { bar.DisplayTime(); } container.Release(bar); // Mimic a time delay. System.Threading.Thread.Sleep(2000); IBar bar2 = container.Resolve<IBar>(); if (bar2 != null) { bar2.DisplayTime(); } container.Release(bar2); Console.Write("Press <ENTER> to exit..."); Console.ReadLine(); }
public void InstallShouldThrowExceptionFromFailedInstaller() { using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); // I would expect NotImplementedException to be thrown here // because it is thrown in the install method of the ExceptionThrowingInstaller // however, what appears to be happening is that after the NotImplementedException // is thrown, the DependencyInstaller never runs, but the "deferred start" code // in OptimizeDependencyResolutionDisposable.Dispose() kicks in anyway // and tries to create the StartableComponent, which it fails to do // because IDependencyOfStartableComponent is not registered // The net effect is that the NotImplementedException thrown by ExceptionThrowingInstaller // is "swallowed" and instead I see a Kernel HandlerException telling me that // IDependencyOfStartableComponent is not registered // expected : Assert.Throws<NotImplementedException>( () => container.Install(new ActionBasedInstaller(c => c.Register(Component.For<UsesIEmptyService>().Start())), new ActionBasedInstaller(c => { throw new NotImplementedException(); }), new ActionBasedInstaller(c => c.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>())))); } }
public void StartableComponentShouldNotStartIfExceptionThrownByInstaller() { UsesIEmptyService.instancesCreated = 0; using (var container = new WindsorContainer()) { container.AddFacility<StartableFacility>(f => f.DeferredStart()); Assert.Throws<NotImplementedException>( () => container.Install(new ActionBasedInstaller(c => c.Register(Component.For<UsesIEmptyService>().Start())), new ActionBasedInstaller(c => c.Register(Component.For<IEmptyService>().ImplementedBy<EmptyServiceA>())), new ActionBasedInstaller(c => { throw new NotImplementedException(); }))); // In this scenario, I've registered IDependencyOfStartableComponent // before the ExceptionThrowingInstaller gets a chance to gum up the works // I would expect that the "deferred start" code NOT run here, // and the StartableComponent remain un-instantiated. // However, Castle is creating the StartableComponent anyway // and then allows the NotImplementedException to bubble out. // Presumably, this is due to the "deferred start" mechanism // being implemented by a using() block or something similar // via OptimizeDependencyResolutionDisposable.Dispose() Assert.AreEqual(0, UsesIEmptyService.instancesCreated); } }
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); }
/// <summary> /// Configure castle windsor as the container creating a new container. /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static Configuration UseCastleWindsor(this Configuration configuration) { ParameterCheck.ParameterRequired(configuration, "configuration"); var container = new WindsorContainer(); return UseCastleWindsor(configuration, container); }
/// <summary> /// Instantiate the container and add all Controllers that derive from /// WindsorController to the container. Also associate the Controller /// with the WindsorContainer ControllerFactory. /// </summary> protected virtual IWindsorContainer InitializeServiceLocator() { IWindsorContainer container = new WindsorContainer(); ComponentRegistrar.AddComponentsTo(container); ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container)); return container; }
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); }
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)); }
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"]); }); }
public void SimpleCase() { String contents = "import Castle.Facilities.AspectSharp.Tests.Components in Castle.Facilities.AspectSharp.Tests " + "import Castle.Facilities.AspectSharp.Tests.Interceptors in Castle.Facilities.AspectSharp.Tests " + " " + " aspect MyAspect for SimpleService " + " " + " pointcut method|property(*)" + " advice(LoggerInterceptor)" + " end" + " " + " end "; MutableConfiguration config = new MutableConfiguration("facility", contents); DefaultConfigurationStore store = new DefaultConfigurationStore(); store.AddFacilityConfiguration("aop", config); WindsorContainer container = new WindsorContainer(store); container.AddFacility( "aop", new AspectSharpFacility() ); container.AddComponent("comp1", typeof(SimpleService)); SimpleService service = container[ typeof(SimpleService) ] as SimpleService; service.DoSomething(); service.DoSomethingElse(); Assert.AreEqual( "Enter DoSomething\r\nEnter DoSomethingElse\r\n", LoggerInterceptor.Messages.ToString() ); }
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); }
public void Init() { if (_initialized) { return; } var container = new WindsorContainer(); var composite = new MvcCompositeApp(container); composite.RegisterNh( MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test-db")), true, false); var compositeAppSettings = new CompositeAppSettings(); compositeAppSettings.OutputChannel.ApplyOverride(typeof(AzureMessageChannel)); compositeAppSettings.BlobStorage.WithDefault(typeof(AzureBlobStorage)); compositeAppSettings.CommandPublicationRecordMapper.WithDefault(typeof(NhRecordMapper<CommandPublicationRecord>)); composite.Configure(compositeAppSettings); /* EUCLID: Install agents and Input models */ composite.AddAgent(typeof(TestCommand).Assembly); container.Register(Component.For<ICompositeApp>().Instance(composite)); setAzureCredentials(container); _initialized = true; }
static async Task AsyncMain() { #region ContainerConfiguration BusConfiguration busConfiguration = new BusConfiguration(); busConfiguration.EndpointName("Samples.Castle"); WindsorContainer container = new WindsorContainer(); container.Register(Component.For<MyService>().Instance(new MyService())); busConfiguration.UseContainer<WindsorBuilder>(c => c.ExistingContainer(container)); #endregion busConfiguration.UseSerialization<JsonSerializer>(); busConfiguration.UsePersistence<InMemoryPersistence>(); busConfiguration.SendFailedMessagesTo("error"); busConfiguration.EnableInstallers(); IEndpointInstance endpoint = await Endpoint.Start(busConfiguration); try { await endpoint.SendLocal(new MyMessage()); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } finally { await endpoint.Stop(); } }
public void SetUp() { var compositeDatabaseConnection = MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test-db")); Container = new WindsorContainer(); setAzureCredentials(Container); Fabric = new ConsoleFabric(Container); var composite = new BasicCompositeApp(Container) { Name = "Euclid.TestingSupport.HostingFabricFixture.Composite", Description = "A composite used in specification tests" }; composite.RegisterNh(compositeDatabaseConnection, false); foreach (var agentAssembly in _agentAssemblies) { composite.AddAgent(agentAssembly); } composite.Configure(getCompositeSettings()); Fabric.Initialize(getFabricSettings()); Fabric.InstallComposite(composite); composite.CreateSchema(compositeDatabaseConnection, true); Fabric.Start(); }
public void AddCoreFromXML() { var container = new WindsorContainer(new XmlInterpreter(new StaticContentResource(@"<castle> <facilities> <facility id='solr' type='Castle.Facilities.SolrNetIntegration.SolrNetFacility, Castle.Facilities.SolrNetIntegration'> <solrURL>http://localhost:8983/solr/defaultCore</solrURL> <cores> <core id='core0-id'> <documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Document, Castle.Facilities.SolrNetIntegration.Tests</documentType> <url>http://localhost:8983/solr/core0</url> </core> <core id='core1-id'> <documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Document, Castle.Facilities.SolrNetIntegration.Tests</documentType> <url>http://localhost:8983/solr/core1</url> </core> <core id='core2-id'> <documentType>Castle.Facilities.SolrNetIntegration.Tests.Tests+Core1Entity, Castle.Facilities.SolrNetIntegration.Tests</documentType> <url>http://localhost:8983/solr/core1</url> </core> </cores> </facility> </facilities> </castle>"))); TestCores(container); }
/// <summary> /// Installs the assemblies. /// </summary> /// <param name = "container">The container.</param> /// <param name = "assemblies">The assemblies.</param> public static void InstallAssemblies(this IIoCContainer container, Assembly[] assemblies) { //Contract.Requires(container != null); //Contract.Requires(assemblies != null); using (var registrationContainer = new WindsorContainer()) { foreach (var assembly in assemblies) { try { //container.Install(FromAssembly.Instance(assembly)); registrationContainer.Register(AllTypes.FromAssembly(assembly) .IncludeNonPublicTypes() .BasedOnAsService<IComponentInstaller>() .Configure(c => c.LifeStyle.Transient)); } catch (Exception e) { var msg = String.Format("Could not load assembly '{0}' because related assembly can't be loaded. Exception details: {1}", assembly.FullName, e.Message); _logger.Fatal(msg, e); throw new Exception(msg); } } foreach (var item in registrationContainer.ResolveAll<IComponentInstaller>()) item.Install(container, assemblies); } }
public void Execute() { var container = new WindsorContainer(); //container.Kernel.ComponentModelBuilder.RemoveContributor( // container.Kernel.ComponentModelBuilder.Contributors.OfType<PropertiesDependenciesModelInspector>().Single()); //container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy(); //container.AddFacility<EventAggregatorFacility>(); container.Register ( Component.For<IWindsorContainer>().Instance(container), Component.For<IViewManager>().ImplementedBy<ViewManager>().LifestyleSingleton(), Component.For<IRMSController>().ImplementedBy<RMSController>().LifestyleSingleton(), Component.For<IEventPublisher>().ImplementedBy<EventPublisher>().LifestyleBoundTo<IService>(), Classes.FromThisAssembly().BasedOn<IView>().WithService.FromInterface().LifestyleTransient(), Classes.FromAssemblyNamed("BTE.RMS.Presentation.Logic.WPF") .BasedOn<WorkspaceViewModel>() .LifestyleTransient(), Classes.FromAssemblyNamed("BTE.RMS.Presentation.Logic.WPF") .BasedOn<IService>() .WithService.FromInterface() .LifestyleSingleton(), Classes.FromAssemblyNamed("BTE.RMS.Presentation.Persistence.WPF") .BasedOn<IRepository>() .WithService.FromInterface() .LifestyleBoundToNearest<IService>() ); var locator = new WindsorServiceLocator(container); ServiceLocator.SetLocatorProvider(() => locator); RMSClientConfig.BaseApiSiteAddress = "http://localhost:9461/"; }
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)); } }
/// <summary>配置默认的Castle容器 /// <remarks>默认使用XmlInterpreter初始化</remarks> /// </summary> /// <param name="configuration"></param> /// <param name="func">执行额外的配置</param> /// <returns></returns> public static Configuration Castle(this Configuration configuration, Action<WindsorResolver> func) { var container = new WindsorContainer(); //从配置文件初始化 container.Install(new ConfigurationInstaller(new XmlInterpreter())); var resolver = new WindsorResolver(container); //设置解释器实例 configuration.Resolver(resolver); //强制注册Log4Net日志工厂+增加注入运行时变量 20111130 resolver.Container.Log4NetLoggerFactory( () => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment) , () => configuration.RuntimeProperties(Configuration.RuntimeProperties_Environment_Error)); //强制设置Common.Logging使用Log4Net实现且使用外部配置的log4net实例 EXTERNAL Common.Logging.LogManager.Adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(new NameValueCollection() { { "configType", "EXTERNAL" } }); //记录启动信息 var log = DependencyResolver .Resolve<ILoggerFactory>() .Create(typeof(ConfigurationExtensions)); log.Info("不启用NamingSubSystem=NamingSubsystemForDefaultComponent,Castle升级至3.0后无需此子系统"); log.Info("强制使用Log4Net日志工厂"); log.Info("强制设置Common.Logging使用Common.Logging.Log4Net实现"); log.Debug("来自Configuration的在日志组件未初始化前的调试信息:\n" + configuration.PopMessages()); //额外的容器配置 func(resolver); return configuration; }
public App() { try { InitializeComponent(); var logger = new ApplicationLogger(); Logger.Register(logger); this.InstallExceptionHandler(new TestExceptionHandler(this, logger, false)); ThreadingFactory.Set(new ApplicationTaskScheduler(logger)); var container = new WindsorContainer(); var configuration = new Configuration.Configuration(container); configuration.Install(); DialogService.ShowMain(new MainViewModel(configuration.BaseApiUrl)); } catch (Exception exception) { Logger.Error(exception); } }
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"); } }
public void SetUp() { _Container = new WindsorContainer(); _Container.AddFacility<AutoTxFacility>(); _Container.Register(Component.For<MyService>()); ThreadPool.SetMinThreads(5, 5); }
public SelectiveExportVm(WindsorContainer applicationWindsorContainer) : base(applicationWindsorContainer) { DispatcherHelper.CheckBeginInvokeOnUI(() => this.View = this.ApplicationOrInvestigationWindsorContainer.Resolve <ISelectiveExportView>()); this._messenger = this.ApplicationOrInvestigationWindsorContainer.Resolve <IDetectiveMessenger>(); Task.Factory.StartNew(() => this._messenger.Register <OpenedInvestigationMessage>(this, this.OpenedInvestigationMessageReceived)); }
public OperationLogVm(WindsorContainer applicationWindsorContainer, OperationLog model) : base(applicationWindsorContainer, model) { DispatcherHelper.CheckBeginInvokeOnUI(() => this.View = this.ApplicationOrInvestigationWindsorContainer.Resolve <IOperationLogView>()); this.OperationLog = model; this.DockPositionPosition = DetectiveDockPosition.DockedBottom; }
protected static void InitializeClass() { Kernel = new WindsorContainer(); Kernel.Install(new DataInstaller()); }
public TRepository Obtain <TRepository>() where TRepository : class { TRepository repository = WindsorContainer.Resolve <TRepository>(new Dictionary <string, object> { { "context", Context } }); if (repository == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Repository of type {0} was not registered by the {1} or could not be constructed using the {2}.", typeof(TRepository).Name, WindsorContainer.GetType().Name, Context.GetType().Name)); } return(repository); }
protected static WindsorContainer CreateContainerForEventStoreType(Func <IReadOnlyList <IEventMigration> > migrationsfactory, Type eventStoreType, string eventStoreConnectionString = null) { var container = new WindsorContainer(); container.ConfigureWiringForTestsCallBeforeAllOtherWiring(); container.Register( Component.For <IUtcTimeTimeSource, DummyTimeSource>() .Instance(DummyTimeSource.Now) .LifestyleSingleton(), Component.For <IServiceBus>() .ImplementedBy <SynchronousBus>() .LifestylePerWebRequest(), Component.For <IEnumerable <IEventMigration> >() .UsingFactoryMethod(migrationsfactory) .LifestylePerWebRequest(), Component.For <IEventStoreSession, IUnitOfWorkParticipant>() .ImplementedBy <EventStoreSession>() .LifestylePerWebRequest(), Component.For <IWindsorContainer>().Instance(container) ); if (eventStoreType == typeof(SqlServerEventStore)) { if (eventStoreConnectionString == null) { var masterConnectionSTring = new ConnectionStringConfigurationParameterProvider().GetConnectionString("MasterDB"); var dbManager = new TemporaryLocalDbManager(masterConnectionSTring.ConnectionString, container); eventStoreConnectionString = dbManager.CreateOrGetLocalDb($"{nameof(EventStreamMutatorTestsBase)}_EventStore"); } container.Register( Component.For <IEventStore>() .ImplementedBy <SqlServerEventStore>() .DependsOn(Dependency.OnValue <string>(eventStoreConnectionString)) .LifestyleScoped()); } else if (eventStoreType == typeof(InMemoryEventStore)) { container.Register( Component.For <IEventStore>() .UsingFactoryMethod( kernel => { var store = kernel.Resolve <InMemoryEventStore>(); store.TestingOnlyReplaceMigrations(migrationsfactory()); return(store); }) .LifestyleScoped(), Component.For <InMemoryEventStore>() .ImplementedBy <InMemoryEventStore>() .LifestyleSingleton()); } else { throw new Exception($"Unsupported type of event store {eventStoreType}"); } container.ConfigureWiringForTestsCallAfterAllOtherWiring(); return(container); }
public void Install(WindsorContainer container, IMapper mapper) { }
public void NoConfig_throws() { var container = new WindsorContainer(); Assert.Throws <FacilityException> (() => container.AddFacility <SolrNetFacility>()); }
private static void RunScenarioWithEventStoreType (MigrationScenario scenario, Type eventStoreType, WindsorContainer container, IList <IEventMigration> migrations, int indexOfScenarioInBatch) { var startingMigrations = migrations.ToList(); migrations.Clear(); var timeSource = container.Resolve <DummyTimeSource>(); IReadOnlyList <IAggregateRootEvent> eventsInStoreAtStart; using (container.BeginScope()) //Why is this needed? It fails without it but I do not understand why... { var eventStore = container.Resolve <IEventStore>(); eventsInStoreAtStart = eventStore.ListAllEventsForTestingPurposesAbsolutelyNotUsableForARealEventStoreOfAnySize(); } Console.WriteLine($"\n########Running Scenario {indexOfScenarioInBatch}"); var original = TestAggregate.FromEvents(DummyTimeSource.Now, scenario.AggregateId, scenario.OriginalHistory).History.ToList(); Console.WriteLine($"Original History: "); original.ForEach(e => Console.WriteLine($" {e}")); Console.WriteLine(); var initialAggregate = TestAggregate.FromEvents(timeSource, scenario.AggregateId, scenario.OriginalHistory); var expected = TestAggregate.FromEvents(timeSource, scenario.AggregateId, scenario.ExpectedHistory).History.ToList(); var expectedCompleteEventstoreStream = eventsInStoreAtStart.Concat(expected).ToList(); Console.WriteLine($"Expected History: "); expected.ForEach(e => Console.WriteLine($" {e}")); Console.WriteLine(); var initialAggregate2 = TestAggregate.FromEvents(timeSource, scenario.AggregateId, scenario.OriginalHistory); timeSource.UtcNow += 1.Hours();//Bump clock to ensure that times will be be wrong unless the time from the original events are used.. Console.WriteLine("Doing pure in memory "); IReadOnlyList <IAggregateRootEvent> otherHistory = SingleAggregateInstanceEventStreamMutator.MutateCompleteAggregateHistory( scenario.Migrations, initialAggregate2.History.Cast <AggregateRootEvent>().ToList()); AssertStreamsAreIdentical(expected, otherHistory, $"Direct call to SingleAggregateInstanceEventStreamMutator.MutateCompleteAggregateHistory"); container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Save(initialAggregate)); migrations.AddRange(startingMigrations); var migratedHistory = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Get <TestAggregate>(initialAggregate.Id)).History; AssertStreamsAreIdentical(expected, migratedHistory, "Loaded un-cached aggregate"); var migratedCachedHistory = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Get <TestAggregate>(initialAggregate.Id)).History; AssertStreamsAreIdentical(expected, migratedCachedHistory, "Loaded cached aggregate"); Console.WriteLine(" Streaming all events in store"); var streamedEvents = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStore>().ListAllEventsForTestingPurposesAbsolutelyNotUsableForARealEventStoreOfAnySize().ToList()); AssertStreamsAreIdentical(expectedCompleteEventstoreStream, streamedEvents, "Streaming all events in store"); Console.WriteLine(" Persisting migrations"); using (container.BeginScope()) { container.Resolve <IEventStore>().PersistMigrations(); } migratedHistory = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Get <TestAggregate>(initialAggregate.Id)).History; AssertStreamsAreIdentical(expected, migratedHistory, "Loaded aggregate"); Console.WriteLine("Streaming all events in store"); streamedEvents = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStore>().ListAllEventsForTestingPurposesAbsolutelyNotUsableForARealEventStoreOfAnySize().ToList()); AssertStreamsAreIdentical(expectedCompleteEventstoreStream, streamedEvents, "Streaming all events in store"); Console.WriteLine(" Disable all migrations so that none are used when reading from the event stores"); migrations.Clear(); migratedHistory = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Get <TestAggregate>(initialAggregate.Id)).History; AssertStreamsAreIdentical(expected, migratedHistory, "loaded aggregate"); Console.WriteLine("Streaming all events in store"); streamedEvents = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStore>().ListAllEventsForTestingPurposesAbsolutelyNotUsableForARealEventStoreOfAnySize().ToList()); AssertStreamsAreIdentical(expectedCompleteEventstoreStream, streamedEvents, "Streaming all events in store"); if (eventStoreType == typeof(SqlServerEventStore)) { Console.WriteLine("Clearing sql server eventstore cache"); container.ExecuteUnitOfWorkInIsolatedScope(() => ((SqlServerEventStore)container.Resolve <IEventStore>()).ClearCache()); migratedHistory = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStoreSession>().Get <TestAggregate>(initialAggregate.Id)).History; AssertStreamsAreIdentical(expected, migratedHistory, "Loaded aggregate"); Console.WriteLine("Streaming all events in store"); streamedEvents = container.ExecuteUnitOfWorkInIsolatedScope(() => container.Resolve <IEventStore>().ListAllEventsForTestingPurposesAbsolutelyNotUsableForARealEventStoreOfAnySize().ToList()); AssertStreamsAreIdentical(expectedCompleteEventstoreStream, streamedEvents, "Streaming all events in store"); } }
private Container() { IocContainer = new WindsorContainer(); IocContainer.Register(Component.For <IReadOnlyDictionary <string, string> >().ImplementedBy <Dictionary <string, string> >().LifeStyle.Transient); }
protected AbstractDaosGuyWire(WindsorContainer container) { this.container = container; }
public ConversationsDetailVm(WindsorContainer applicationWindsorContainer, IConversationsVm model) : base(applicationWindsorContainer, model) { this.ConversationsVm = model; DispatcherHelper.CheckBeginInvokeOnUI(() => this.View = this.ApplicationOrInvestigationWindsorContainer.Resolve <IConversationsDetailView>()); }
public void NoConfig_throws() { var container = new WindsorContainer(); container.AddFacility <SolrNetFacility>(); }
protected override void Initialize(WindsorContainer container) { this.dependencyResolver = new WindsorDependencyResolver(container); }
public NetfoxDbContextInMemory(WindsorContainer windsorContainer, SqlConnectionStringBuilder sqlConnectionStringBuilder) : base(windsorContainer, sqlConnectionStringBuilder) { }
public GenericEventsExplorerVm(WindsorContainer applicationWindsorContainer) : base(applicationWindsorContainer) { this.DockPositionPosition = DetectiveDockPosition.DockedLeft; Parallel.Invoke(() => Messenger.Default.Register <ExportResultMessage>(this, this.ExportResultActionHandler)); }
public void Install(IWindsorContainer container, IConfigurationStore store) { var childContainer = new WindsorContainer( "Improving.MediatR", new DefaultKernel(), new DefaultComponentInstaller()); childContainer.Kernel.Resolver.AddSubResolver(new EnvironmentResolver()); childContainer.Kernel.Resolver.AddSubResolver( new ArrayResolver(childContainer.Kernel, true)); childContainer.Kernel.AddHandlersFilter(new RestHandlerFilter()); childContainer.Kernel.AddHandlersFilter( new OpenGenericHandlersFilter(typeof(BatchOf <,>), typeof(BatchHandler <,>))); childContainer.Kernel.AddHandlersFilter( new OpenGenericHandlersFilter(typeof(Cached <>), typeof(CacheHandler <>))); childContainer.Kernel.AddHandlersFilter( new OpenGenericHandlersFilter(typeof(Routed <>), typeof(RouteHandler <>))); childContainer.Kernel.AddHandlersFilter(new ContravariantFilter()); childContainer.Kernel.AddHandlerSelector(new PipelineSelector()); childContainer.Register( Component.For <IMediator>().ImplementedBy <ScopedMediator>(), Component.For <EnvironmentInterceptor>().LifestyleTransient() ); childContainer.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated; foreach (var assembly in _fromAssemblies .Concat(new[] { Classes.FromThisAssembly() })) { childContainer.Register(assembly .BasedOn(typeof(IRequestHandler <,>)) .OrBasedOn(typeof(IRequestMiddleware <,>)) .OrBasedOn(typeof(IAsyncRequestHandler <,>)) .OrBasedOn(typeof(INotificationHandler <>)) .OrBasedOn(typeof(IAsyncNotificationHandler <>)) .OrBasedOn(typeof(IValidator <>)) .OrBasedOn(typeof(IRouter)) .WithServiceBase() .Configure(c => { if (c.Implementation != null && typeof(IRouter).IsAssignableFrom(c.Implementation)) { return; } c.LifestyleScoped(); c.Proxy.Hook(new EnvironmentProxyGenerationHook()) .Interceptors <EnvironmentInterceptor>(); if (c.Implementation != null) { var requiresMatching = c.Implementation.GetInterface( typeof(IRequireGenericMatching <>).FullName); if (requiresMatching == null) { return; } var matcher = requiresMatching.GetGenericArguments()[0]; c.ExtendedProperties( Property.ForKey(Constants.GenericImplementationMatchingStrategy) .Eq(Activator.CreateInstance(matcher))); } })); } container.Register(Component.For <IValidatorFactory>() .ImplementedBy <WindsorValidatorFactory>() .OnlyNewServices()); container.AddChildContainer(childContainer); container.Register(Component.For <IMediator>() .Instance(childContainer.Resolve <IMediator>())); }
public FrameContentVm(WindsorContainer applicationWindsorContainer, FrameVm model) : base(applicationWindsorContainer, model) { this.FrameVm = model; DispatcherHelper.CheckBeginInvokeOnUI(() => this.View = this.ApplicationOrInvestigationWindsorContainer.Resolve <IFrameContentView>()); }
public void SetUp() { container = new WindsorContainer(); }
public override bool OnStart() { ServicePointManager.DefaultConnectionLimit = 1000; ThreadPool.SetMinThreads(100, 100); var container = new WindsorContainer(); var serviceLocator = new WindsorServiceLocator(container); _configurationValueProvider = new AzureConfigurationValueProvider(); var storageConnectionString = _configurationValueProvider.GetValue(ConfigurationKeys.TableStorageConnectionString); var servicebusConnectionString = _configurationValueProvider.GetValue(ConfigurationKeys.ServiceBusConnectionString); container.Register( Component.For <Orchestrator>() .ImplementedBy <Orchestrator>() .LifestyleSingleton(), Component.For <MasterScheduler>() .ImplementedBy <MasterScheduler>() .LifestyleSingleton(), Component.For <IConfigurationValueProvider>() .Instance(_configurationValueProvider), Component.For <IServiceLocator>() .Instance(serviceLocator), Component.For <IActorConfiguration>() .Instance( ActorDescriptors.FromAssemblyContaining <PeckSourceScheduled>() .ToConfiguration()), Component.For <IFactoryActor>() .ImplementedBy <FactoryActor>() .LifestyleTransient(), Component.For <PeckSourceProcessor>() .ImplementedBy <PeckSourceProcessor>() .LifestyleTransient(), Component.For <ILockStore>() .Instance(new AzureLockStore(new BlobSource() { ConnectionString = storageConnectionString, ContainerName = "locks", Path = "woodpecker/locks/master_Keys/" })), Component.For <IEventQueueOperator>() .Instance(new ServiceBusOperator(servicebusConnectionString)) ); _orchestrator = container.Resolve <Orchestrator>(); _scheduler = container.Resolve <MasterScheduler>(); Task.Run(() => _orchestrator.SetupAsync()).Wait(); _orchestrator.Start(); Console.WriteLine("Working ..."); // For information on handling configuration changes // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. bool result = base.OnStart(); Trace.TraceInformation("Woodpecker.Worker.Role has been started"); return(result); }
public ConversationVm(WindsorContainer applicationWindsorContainer, ILxConversation model) : base(applicationWindsorContainer, model) { this.Conversation = model; this._messenger = applicationWindsorContainer.Resolve <IDetectiveMessenger>(); }
public ConstructorDependencyWithInterfaces_Tests() { _container = new WindsorContainer(); }
public void Setup() { _container = new WindsorContainer(); RepositoryInstaller.InstallForTest(_container); _scope = _container.BeginScope(); }