static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            if (MicroserviceHost.ShouldRunAsService(args))
            {
                host.RunAsService();
            }
            else
            {
                host.Run();
            }
        }
    public void MicroserviceHostWithoutHandlersFails()
    {
        var serviceMock = new EmptyServiceMock();
        MicroserviceConfigurationException ex =
            Assert.Throws <MicroserviceConfigurationException>(() =>
        {
            using (var host = new MicroserviceHost <EmptyServiceMock>(serviceMock))
            {
            }
        });

        Assert.Equal("No Handlers can be found in the Microservice interface.", ex.Message);
    }
    public void MicroserviceHostWithoutConfiguredQueueNameFails()
    {
        var serviceMock = new ServiceWithoutQueueMock();
        MicroserviceConfigurationException ex =
            Assert.Throws <MicroserviceConfigurationException>(() =>
        {
            using (var host = new MicroserviceHost <ServiceWithoutQueueMock>(serviceMock))
            {
                host.Open();
            }
        });

        Assert.Equal("No queue name is configured in the MicroserviceAtrribute on any Microservice interface nor in the Busoptions.", ex.Message);
    }
    public void MicroserviceHostFailsIfRabbitMQIsNotReachable()
    {
        var serviceMock = new SomeMicroserviceMock();
        var options     = new BusOptions {
            HostName = "NonExistingName"
        };
        MicroserviceConfigurationException ex =
            Assert.Throws <MicroserviceConfigurationException>(() =>
        {
            using (var host = new MicroserviceHost <SomeMicroserviceMock>(serviceMock, options))
            {
                host.Open();
            }
        });

        Assert.Equal("The Eventbus (RabbitMQ service) cannot be reached.", ex.Message);
    }
示例#5
0
        public void NamedKernelModuleLoadedFirstInFrameworkModules()
        {
            //-- arrange

            var logger = new MicroserviceHostLoggerMock();
            var config = CreateBootConfiguration();

            config.MicroserviceConfig.FrameworkModules = new MicroserviceConfig.ModuleConfig[]
            {
                new MicroserviceConfig.ModuleConfig()
                {
                    Assembly = "NWheels.Implementation",
                    Features = new MicroserviceConfig.ModuleConfig.FeatureConfig[] {
                        new MicroserviceConfig.ModuleConfig.FeatureConfig()
                        {
                            Name = "NamedKernelFeatureLoader"
                        }
                    }
                }
            };
            var host    = new MicroserviceHost(config, logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += (object sender, AssemblyLoadEventArgs e) =>
            {
                if (e.ImplementedInterface == typeof(IFeatureLoader))
                {
                    if (e.AssemblyName == "NWheels.Implementation")
                    {
                        e.Destination.Add(typeof(NamedKernelFeatureLoader));
                    }
                }
            };
            host.AssemblyLoad += handler.Handle;

            //-- act

            host.Configure();

            //-- assert

            var logs = logger.TakeLog();

            logs.Skip(1 + 2).First().Should().Be(
                "FoundFeatureLoaderComponent(component=NamedKernelFeatureLoader)");
        }
    public void MicroserviceHostSilentlyIgnoresUnknownCommands()
    {
        var serviceMock = new SomeMicroserviceMock();

        using (var host = new MicroserviceHost <SomeMicroserviceMock>(serviceMock))
        {
            var options = new BusOptions()
            {
                QueueName = "microserviceQueue"
            };
            var command = new KeyValuePair <string, int>("Test", 42);
            SendMessage(command, options);
            serviceMock.ReceivedFlag.WaitOne(500);

            Assert.False(serviceMock.SomeCommandHandlerHasBeenCalled);
            Assert.False(serviceMock.TestCommandHandlerHasBeenCalled);
        }
    }
    public void HandlerNotInInterfaceShouldNotBeTriggered2()
    {
        var options = new BusOptions()
        {
            QueueName = "TestQueue02"
        };
        var serviceMock = new HalfServiceMock();

        using (var host = new MicroserviceHost <HalfServiceMock>(serviceMock, options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                var command = new TestCommand();
                proxy.Execute(command);

                Thread.Sleep(500);
                Assert.True(serviceMock.TestCommandHandlerHasBeenCalled);
            }
    }
        public void GetCompileRegistredComponentAfterConfiguring()
        {
            //-- arrange

            var logger  = new MicroserviceHostLoggerMock();
            var host    = new MicroserviceHost(CreateBootConfiguration(), logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            //-- act

            host.Configure();
            var container = host.GetContainer();
            var component = container.Resolve <ICompileRegistered>();

            //-- assert

            component.Should().NotBeNull();
        }
示例#9
0
        public void CreateListenerIsCalledOnce(int listenerAmount)
        {
            // Arrange
            var contextMock  = new Mock <IBusContext <IConnection> >();
            var receiverMock = new Mock <IMessageReceiver>();
            var logger       = new Mock <ILogger <MicroserviceHost> >();

            contextMock.Setup(e => e.CreateMessageReceiver(It.IsAny <string>(), It.IsAny <IEnumerable <string> >()))
            .Returns(receiverMock.Object);

            var listeners = Enumerable.Range(0, listenerAmount).Select(e => new MicroserviceListener());

            var host = new MicroserviceHost(contextMock.Object, listeners, new List <MicroserviceCommandListener>(), "test.queue", logger.Object);

            // Act
            host.Start();

            // Assert
            contextMock.Verify(e => e.CreateMessageReceiver(It.IsAny <string>(), It.IsAny <IEnumerable <string> >()), Times.Once);
        }
示例#10
0
        public void InjectionAdapterLoadedFirst()
        {
            //-- arrange

            var logger  = new MicroserviceHostLoggerMock();
            var host    = new MicroserviceHost(CreateBootConfiguration(), logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            //-- act

            host.Configure();

            //-- assert

            var logs = logger.TakeLog();
            var firstLoadedComponent = logs.FirstOrDefault(x => x.StartsWith("FoundFeatureLoaderComponent"));

            firstLoadedComponent.Should().Be("FoundFeatureLoaderComponent(component=ComponentContainerBuilder)");
        }
示例#11
0
        public void TryDiscoverUnexistedFeatureLoaderOnConfiguring()
        {
            //-- arrange

            var logger = new MicroserviceHostLoggerMock();
            var config = CreateBootConfiguration();

            config.MicroserviceConfig.ApplicationModules[0].Features[0].Name = "Abracadabra";
            var host    = new MicroserviceHost(config, logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            //-- act

            Action configuring = () => host.Configure();

            //-- assert

            configuring.ShouldThrow <Exception>();
        }
    public void MicroServiceReturnsValue()
    {
        var options = new BusOptions()
        {
            QueueName = "CallbackTest01"
        };
        var serviceMock = new CallbackMock();

        using (var host = new MicroserviceHost <CallbackMock>(serviceMock, options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                RequestCommand requestCommand = new RequestCommand {
                    Name = "Marco"
                };
                TestResponse response = proxy.Execute <TestResponse>(requestCommand);

                Assert.Equal("Hello, Marco", response.Greeting);
            }
    }
示例#13
0
        public void CanExecuteFeatureLoadersLifecycle()
        {
            //-- arrange

            var host    = new MicroserviceHost(CreateBootConfiguration(), new MicroserviceHostLoggerMock());
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            var featureLoaderLog = new List <string>();

            AddFeatureLoaderLoggingInterceptor <FirstFeatureLoader>(featureLoaderLog);
            AddFeatureLoaderLoggingInterceptor <SecondFeatureLoader>(featureLoaderLog);

            //-- act

            host.Configure();

            //-- assert

            featureLoaderLog.Should().Equal(
                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeConfigSections)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeConfigSections)}",

                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeConfiguration)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeConfiguration)}",

                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeComponents)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeComponents)}",

                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeAdapterComponents)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeAdapterComponents)}",

                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.CompileComponents)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.CompileComponents)}",

                $"{typeof(FirstFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeCompiledComponents)}",
                $"{typeof(SecondFeatureLoader).Name}.{nameof(IFeatureLoader.ContributeCompiledComponents)}"
                );
        }
示例#14
0
        public void ResumingTriggersHostResumedEventWithProperValues()
        {
            // Arrange
            var contextMock  = new Mock <IBusContext <IConnection> >();
            var receiverMock = new Mock <IMessageReceiver>();
            var logger       = new Mock <ILogger <MicroserviceHost> >();

            const string queue = "testQueue";

            string[] topics = { "Topic1", "Topic2" };

            contextMock.Setup(e => e.CreateMessageReceiver(queue, topics))
            .Returns(receiverMock.Object);

            var listeners = new[] { new MicroserviceListener {
                                        TopicExpressions = topics
                                    } };

            var host = new MicroserviceHost(contextMock.Object, listeners, new List <MicroserviceCommandListener>(), queue, logger.Object);

            host.Start();
            host.Pause();

            IMicroserviceHost    resultHost = null;
            HostResumedEventArgs eventArgs  = null;

            host.HostResumed += (microserviceHost, args) =>
            {
                resultHost = microserviceHost;
                eventArgs  = args;
            };

            // Act
            host.Resume();

            // Assert
            Assert.AreEqual(host, resultHost);
            Assert.IsNotNull(eventArgs);
        }
示例#15
0
        public void CheckNamedByAttributeFeatureLoadersDiscoveredOnConfiguring()
        {
            //-- arrange

            var logger  = new MicroserviceHostLoggerMock();
            var host    = new MicroserviceHost(CreateBootConfiguration(), logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            //-- act

            host.Configure();

            //-- assert

            var logs = logger.TakeLog();

            logs.Should().Contain(new string[] {
                "FoundFeatureLoaderComponent(component=NamedFeatureLoader)"
            });
        }
示例#16
0
        public void KernelModulesDefaultFeatureLoadersLoadedFirstAfterInjectionAdapter()
        {
            //-- arrange

            var logger  = new MicroserviceHostLoggerMock();
            var host    = new MicroserviceHost(CreateBootConfiguration(), logger);
            var handler = new AssemblyLoadEventHandler();

            host.AssemblyLoad += handler.Handle;

            //-- act

            host.Configure();

            //-- assert

            var logs = logger.TakeLog();

            logs.Skip(1).Take(2).OrderBy(x => x).Should().Equal(new string[] {
                "FoundFeatureLoaderComponent(component=CompilationFeatureLoader)",
                "FoundFeatureLoaderComponent(component=InvocationSchedulerFeatureLoader)",
            });
        }
    public void MicroServiceThrowsException()
    {
        // Arrange
        var options = new BusOptions()
        {
            QueueName = "ExceptionThrowingTest01"
        };

        using (var host = new MicroserviceHost <ExceptionThrowingService>(options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                // Act
                WorkCommand command = new WorkCommand {
                    Name = "Marco"
                };
                Action action = () => proxy.Execute(command);

                // Assert
                Assert.Throws <NotImplementedException>(action);
            }
    }
    public void HandlerNotInInterfaceShouldNotBeTriggered()
    {
        var options = new BusOptions()
        {
            QueueName = "TestQueue01"
        };
        var serviceMock = new HalfServiceMock();

        using (var host = new MicroserviceHost <HalfServiceMock>(serviceMock, options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                var command = new SomeCommand()
                {
                    SomeValue = "teststring"
                };
                Action action = () => proxy.Execute(command);

                Assert.Throws <MicroserviceException>(action);
                Assert.False(serviceMock.SomeCommandHandlerHasBeenCalled);
            }
    }
    public void MicroserviceHostReceivesCommands()
    {
        var serviceMock = new SomeMicroserviceMock();

        using (var host = new MicroserviceHost <SomeMicroserviceMock>(serviceMock))
        {
            var options = new BusOptions()
            {
                QueueName = "microserviceQueue"
            };

            host.Open();

            var command = new SomeCommand()
            {
                SomeValue = "teststring"
            };
            SendMessage(command, options);
            serviceMock.ReceivedFlag.WaitOne(500);

            Assert.True(serviceMock.SomeCommandHandlerHasBeenCalled);
            Assert.False(serviceMock.TestCommandHandlerHasBeenCalled);
        }
    }
    public void ProxySendsCommands()
    {
        var options = new BusOptions()
        {
            QueueName = "ProxyTestQueue01"
        };
        var serviceMock = new OtherMicroserviceMock();

        using (var host = new MicroserviceHost <OtherMicroserviceMock>(serviceMock, options))
            using (var proxy = new MicroserviceProxy(options))
            {
                host.Open();

                var command = new SomeCommand()
                {
                    SomeValue = "teststring"
                };
                proxy.Execute(command);

                Thread.Sleep(500);

                Assert.True(serviceMock.SomeCommandHandlerHasBeenCalled);
            }
    }
示例#21
0
        public void CreateListenerIsCalledWithProperParameters(string queueName, string topics)
        {
            // Arrange
            var contextMock  = new Mock <IBusContext <IConnection> >();
            var receiverMock = new Mock <IMessageReceiver>();
            var logger       = new Mock <ILogger <MicroserviceHost> >();

            string[] topicNames = topics.Split(',');

            contextMock.Setup(e => e.CreateMessageReceiver(queueName, topicNames))
            .Returns(receiverMock.Object);

            var listeners = new[] { new MicroserviceListener {
                                        TopicExpressions = topicNames
                                    } };

            var host = new MicroserviceHost(contextMock.Object, listeners, new List <MicroserviceCommandListener>(), queueName, logger.Object);

            // Act
            host.Start();

            // Assert
            contextMock.Verify(e => e.CreateMessageReceiver(queueName, topicNames));
        }
示例#22
0
        public void Initialize()
        {
            connection = new SqliteConnection("DataSource=:memory:");
            connection.Open();
            options = new DbContextOptionsBuilder <BeheerContext>()
                      .UseSqlite(connection)
                      .Options;

            using (var context = new BeheerContext(options))
            {
                context.Database.EnsureCreated();
                var artikel = new Artikel
                {
                    Artikelnummer  = 1,
                    Beschrijving   = "Grote fiets voor iedereen",
                    LeverbaarTot   = new DateTime(2018, 5, 5),
                    LeverbaarVanaf = new DateTime(2017, 1, 1),
                    Naam           = "Fiets",
                    Prijs          = 40m,
                    Voorraad       = 5
                };
                var artikel2 = new Artikel
                {
                    Artikelnummer  = 2,
                    Beschrijving   = "HELE grote fiets voor iedereen",
                    LeverbaarTot   = new DateTime(2018, 5, 5),
                    LeverbaarVanaf = new DateTime(2017, 1, 1),
                    Naam           = "Fiets Groot",
                    Prijs          = 100m,
                    Voorraad       = 8
                };
                var klant = new Klant {
                    Voornaam = "Hans", Achternaam = "Van Huizen", Id = "1"
                };

                var klantDatamapper = new KlantDatamapper(context);
                klantDatamapper.Insert(klant);

                var datamapper = new ArtikelDatamapper(context);
                datamapper.Insert(artikel);
                datamapper.Insert(artikel2);
            }


            _context = new TestBusContext();

            var services = new ServiceCollection();

            services.AddTransient <ICommandPublisher, CommandPublisher>();
            services.AddSingleton <DbContextOptions>(options);
            services.AddTransient <BeheerContext, BeheerContext>();
            services.AddTransient <IArtikelDatamapper, ArtikelDatamapper>();
            services.AddTransient <IBestellingDatamapper, BestellingDatamapper>();
            services.AddSingleton <IBusContext <IConnection> >(_context);
            services.AddTransient <IEventPublisher, EventPublisher>();
            services.AddTransient <IKlantDatamapper, KlantDatamapper>();

            var builder = new MicroserviceHostBuilder()
                          .RegisterDependencies(services)
                          .WithContext(_context)
                          .AddCommandListener <BestellingListener>()
                          .AddCommandListener <BestellingListenerIntegratieTest>()
                          .AddEventListener <BestellingListener>();

            _host = builder.CreateHost();

            _host.StartListening();
        }
示例#23
0
 /// <summary>
 /// It's important to have this methods defined as follows in order to prevent issues with EF
 /// migrations https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
 /// </summary>
 public static IWebHost BuildWebHost(string[] args) => MicroserviceHost
 .Build <Startup>(args);
示例#24
0
 public void StartListening(MicroserviceHost host)
 {
     Host = host;
 }