public async Task InMemoryEventBus_PublishEventAsync_OneHandlerInError_Should_NotDispatch_MultipleTimes_ToSuccessfullHandlers()
        {
            var errorEvent = new ErrorEvent();
            var b          = new InMemoryEventBus(new InMemoryEventBusConfigurationBuilder()
                                                  .SetRetryStrategy(1, 2).Build());

            (await b.PublishEventAsync(errorEvent)).IsSuccess.Should().BeFalse();

            errorEvent.Data.Should().Be("1222");
        }
Beispiel #2
0
        public async Task InMemoryEventBus_PublishEventAsync_Should_Respect_Priority()
        {
            var b = new InMemoryEventBus();

            s_OrderString.Should().BeNullOrWhiteSpace();

            (await b.PublishEventAsync(new OrderedEvent()).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            s_OrderString.Should().Be("HNL");
        }
Beispiel #3
0
 public void SetUp()
 {
     this.eventBus  = new InMemoryEventBus();
     this.operation = new Parser(new Lexer()).Parse(new Source(@"
         subscription testSub {
             newMessages(author : ""Bob"") {
                 content
             }
         }
     "));
 }
Beispiel #4
0
        public async Task Publish_Event_CriticalHandlerThrow_Should_NotCallNextHandlers()
        {
            var evt        = new CriticalEvent();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder();
            var bus = new InMemoryEventBus(cfgBuilder.Build());

            (await bus.PublishEventAsync(evt)).IsSuccess.Should().BeTrue();

            evt.HandlerData.Should().Be("AB");
        }
Beispiel #5
0
        public async Task InMemoryEventBus_PublishEventAsync_HandlerInDispatcher()
        {
            CoreDispatcher.AddHandlerToDispatcher(new TestEventContextHandler(1));
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(1);
        }
Beispiel #6
0
 protected override void Given()
 {
     var eventBus = new InMemoryEventBus(new MessageRouterStub());
     var eventStore = new StubEventStore(eventBus);
     var events = new List<IDomainEvent>();
     events.Add(new ValidEvent(Guid.Empty) { EventNumber = 0 });
     events.Add(new AnotherValidEvent(Guid.Empty) { EventNumber = 1 });
     events.Add(new ValidEvent(Guid.Empty) { EventNumber = 2 });
     events.Add(new AnotherValidEvent(Guid.Empty) { EventNumber = 3 });
     eventStore.InsertEvents(events);
     _aggregate = eventStore.Get<StubAggregate>(Guid.Empty);
 }
Beispiel #7
0
        public async Task InMemoryEventBus_PublishEventAsync_ContextAsHandler()
        {
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }, new TestEventContextHandler(0)).ConfigureAwait(false))
            .IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(0);
        }
        public async Task PublishEventRange_SameEventType_SameAggId_NoParallel(int nbEvents)
        {
            var  bus    = new InMemoryEventBus();
            var  events = new List <IDomainEvent>();
            Guid aggId  = Guid.NewGuid();

            for (int i = 0; i < nbEvents; i++)
            {
                events.Add(new TestDispatchEvent(i, MillisecondsJobDuration != 0, MillisecondsJobDuration,
                                                 aggId, typeof(object)));
            }
            await bus.PublishEventRangeAsync(events);
        }
Beispiel #9
0
        public async Task Publish_Event_CriticalHandlerThrow_Should_BeTheOnlyOneRetried_If_RetryStrategy_IsDefined()
        {
            var evt        = new CriticalEvent();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(1, 3);
            var bus = new InMemoryEventBus(cfgBuilder.Build());

            (await bus.PublishEventAsync(evt)).IsSuccess.Should().BeTrue();

            evt.HandlerData.Should().Be("ABBBC");
            evt.NbTries.Should().Be(3);
        }
Beispiel #10
0
 internal static void ConfigureInMemoryEventBus(Bootstrapper bootstrapper, InMemoryEventBusConfiguration?configuration, string[] excludedEventsDLLs, BootstrappingContext ctx)
 {
     InMemoryEventBus.InitHandlersCollection(excludedEventsDLLs);
     if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
     {
         bootstrapper.AddIoCRegistration(new TypeRegistration(typeof(InMemoryEventBus), typeof(IDomainEventBus), typeof(InMemoryEventBus)));
         if (configuration != null)
         {
             bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(configuration, typeof(InMemoryEventBusConfiguration)));
         }
     }
     bootstrapper.AddNotifications(PerformEventChecksAccordingToBootstrapperParameters(ctx, configuration));
 }
Beispiel #11
0
        public static IContainer BuildContainer()
        {
            var builder = new ContainerBuilder();

            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // mediator itself
            builder
            .RegisterType <Mediator>()
            .As <IMediator>()
            .InstancePerLifetimeScope();

            // request handlers
            builder
            .Register <SingleInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve <IComponentContext>();
                return(t => { object o; return c.TryResolve(t, out o) ? o : null; });
            })
            .InstancePerLifetimeScope();

            // notification handlers
            builder
            .Register <MultiInstanceFactory>(ctx =>
            {
                var c = ctx.Resolve <IComponentContext>();
                return(t => (IEnumerable <object>)c.Resolve(typeof(IEnumerable <>).MakeGenericType(t)));
            })
            .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(typeof(FaturasCommandHandler).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan

            builder.Register(ctx =>
            {
                var bus = new InMemoryEventBus(ctx.Resolve <ILifetimeScope>());

                bus.Subscribe <SalvarFaturaCommand, FaturasCommandHandler>();
                bus.Subscribe <NovaFaturaSalvaEvent, NovaFaturaSalvaEventHandler>();

                return(bus);
            })
            .AsImplementedInterfaces()
            .SingleInstance();

            builder.RegisterType <InMemorySubscriptionsManager>()
            .AsImplementedInterfaces()
            .SingleInstance();

            return(builder.Build());
        }
Beispiel #12
0
        public async Task InMemoryEventBus_Configuration_RetryStrategy_CallbackNoInvoked()
        {
            bool callbackCalled = false;
            var  cfgBuilder     =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(100, 3)
                .DefineErrorCallback((e, ctx) => callbackCalled = true);

            var b = new InMemoryEventBus(cfgBuilder.Build());

            (await b.PublishEventAsync(new TestRetryEvent()).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            callbackCalled.Should().BeFalse();
        }
Beispiel #13
0
        public async Task InMemoryEventBus_Configuration_ParallelDispatch()
        {
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .AllowParallelDispatchFor <ParallelEvent>();

            var b = new InMemoryEventBus(cfgBuilder.Build());

            var evt = new ParallelEvent();

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            evt.ThreadsInfos.Should().HaveCount(2);
        }
Beispiel #14
0
 internal RabbitMQServer(
     ILoggerFactory loggerFactory,
     RabbitMQServerConfiguration config = null,
     InMemoryEventBus inMemoryEventBus  = null)
 {
     if (loggerFactory == null)
     {
         loggerFactory = new LoggerFactory();
         loggerFactory.AddProvider(new DebugLoggerProvider());
     }
     _logger           = loggerFactory.CreateLogger <RabbitMQServer>();
     _config           = config ?? RabbitMQServerConfiguration.Default;
     _inMemoryEventBus = inMemoryEventBus;
 }
Beispiel #15
0
 protected override void Given()
 {
     _stubEventBus = new InMemoryEventBus(new MessageRouterStub());
     _publishedEvents = new List<IDomainEvent>();
     _stubEventBus.EventPublished = (y) => _publishedEvents.Add(y);
     _eventStore = new StubEventStore(_stubEventBus);
     _aggregate = new StubAggregate();
     _aggregate.DoThis();
     _aggregate.DoSomethingElse();
     _aggregate.DoThis();
     _aggregate.DoSomethingElse();
     _eventStore.Insert(_aggregate);
     _eventStore.Commit();
 }
Beispiel #16
0
        /// <summary>
        /// Configure the system to use InMemory Event bus for dipsatching events, with the provided configuration.
        /// </summary>
        /// <param name="bootstrapper">Bootstrapper instance.</param>
        /// <param name="configurationBuilderAction">Action to apply on builder.</param>
        /// <param name="excludedEventsDLLs">DLLs name to exclude from auto-configuration into IoC
        /// (IAutoRegisterType will be ineffective).</param>
        /// <returns>Bootstrapper Instance.</returns>
        public static Bootstrapper UseInMemoryEventBus(this Bootstrapper bootstrapper, Action <InMemoryEventBusConfigurationBuilder> configurationBuilderAction,
                                                       params string[] excludedEventsDLLs)
        {
            if (configurationBuilderAction == null)
            {
                throw new ArgumentNullException(nameof(configurationBuilderAction));
            }

            InMemoryEventBus.InitHandlersCollection(excludedEventsDLLs);
            var builder = new InMemoryEventBusConfigurationBuilder();

            configurationBuilderAction(builder);

            return(UseInMemoryEventBus(bootstrapper, builder.Build()));
        }
Beispiel #17
0
        public void Init(IUnityContainer container)
        {
            Database.DefaultConnectionFactory = new ConnectionFactory(Database.DefaultConnectionFactory);
            Database.SetInitializer<SketchDbContext>(null);
            Database.SetInitializer<EventStoreDbContext>(null);

            container.RegisterType<ITextSerializer, JsonSerializer>();
            var eventBus = new InMemoryEventBus();
            container.RegisterInstance<IEventBus>(eventBus);

            foreach (var handler in container.ResolveAll<IEventHandler>())
            {
                eventBus.Register(handler);
            }
        }
Beispiel #18
0
 internal MSMQServer(string emiter, ILoggerFactory loggerFactory, InMemoryEventBus inMemoryEventBus = null,
                     QueueConfiguration configuration = null)
 {
     if (string.IsNullOrWhiteSpace(emiter))
     {
         throw new ArgumentNullException(nameof(emiter));
     }
     if (loggerFactory == null)
     {
         loggerFactory = new LoggerFactory();
         loggerFactory.AddProvider(new DebugLoggerProvider());
     }
     _logger           = loggerFactory.CreateLogger <MSMQServer>();
     _emiter           = emiter;
     _inMemoryEventBus = inMemoryEventBus;
     _configuration    = configuration;
 }
Beispiel #19
0
        public async Task InMemoryEventBus_PublishEventAsync_HandlerSameInstance_Should_NotBeCalledTwice()
        {
            TestEventContextHandler.CallTimes = 0;
            var h = new TestEventContextHandler(1);

            CoreDispatcher.AddHandlerToDispatcher(new TestEventContextHandler(1));
            CoreDispatcher.AddHandlerToDispatcher(h);
            CoreDispatcher.AddHandlerToDispatcher(h);

            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestEvent {
                Data = "to_ctx"
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestEventContextHandler.Data.Should().Be("to_ctx");
            TestEventContextHandler.Dispatcher.Should().Be(1);
            TestEventContextHandler.CallTimes.Should().Be(1);
        }
        public async Task InMemoryEventBus_ResolutionError_Type_IsSubViewModel_Should_NotLogAnything()
        {
            var scopeMock         = new Mock <IScope>();
            var fakeLogger        = new FakeLogger(LogLevel.Error);
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(fakeLogger);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(typeof(SubViewModel), It.IsAny <IResolverParameter[]>())).Throws(new Exception());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new SubVMEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            fakeLogger.CurrentLogValue.Should().BeNullOrEmpty();
            fakeLogger.NbLogs.Should().Be(0);
        }
        public async Task PublishEventRange_SameEventType_AllDifferentAggId_AllParallel(int nbEvents)
        {
            var bus = new InMemoryEventBus(new InMemoryEventBusConfiguration
            {
                _parallelHandling = new List <Type> {
                    typeof(TestDispatchEvent)
                },
                _parallelDispatch = new List <Type> {
                    typeof(TestDispatchEvent)
                }
            });
            var events = new List <IDomainEvent>();

            for (int i = 0; i < nbEvents; i++)
            {
                events.Add(new TestDispatchEvent(i, MillisecondsJobDuration != 0, MillisecondsJobDuration,
                                                 Guid.NewGuid(), typeof(object)));
            }
            await bus.PublishEventRangeAsync(events);
        }
Beispiel #22
0
        public void Init(IUnityContainer container)
        {
            container.RegisterType<ITextSerializer, JsonSerializer>();
            var eventBus = new InMemoryEventBus();
            container.RegisterInstance<IEventBus>(eventBus);
            var commandBus = new InMemoryCommandBus();
            container.RegisterInstance<ICommandBus>(commandBus);

            container.RegisterType<IEventStore, SqlEventStore>();

            foreach (var handler in container.ResolveAll<ICommandHandler>())
            {
                commandBus.Register(handler);
            }

            foreach (var handler in container.ResolveAll<IEventHandler>())
            {
                eventBus.Register(handler);
            }
        }
Beispiel #23
0
        public async Task InMemoryEventBus_ResolutionError_Type_IsSubViewModel_Should_NotLogAnything()
        {
            var scopeMock         = new Mock <IScope>();
            var loggerMock        = new Mock <ILogger>();
            var loggerFactoryMock = new Mock <ILoggerFactory>();

            loggerFactoryMock.Setup(m => m.CreateLogger(It.IsAny <string>())).Returns(loggerMock.Object);

            scopeMock.Setup(m => m.Resolve <ILoggerFactory>(It.IsAny <IResolverParameter[]>()))
            .Returns(loggerFactoryMock.Object);

            scopeMock.Setup(m => m.Resolve(typeof(SubViewModel), It.IsAny <IResolverParameter[]>())).Throws(new Exception());

            var b = new InMemoryEventBus(null, new TestScopeFactory(scopeMock.Object));

            (await b.PublishEventAsync(new SubVMEvent()).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            loggerMock.Verify(x =>
                              x.Log(LogLevel.Error, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()), Times.Never());
        }
Beispiel #24
0
 public void ShouldNotFail()
 {
     var id = Guid.NewGuid();
     var eventPublisher = new InMemoryEventBus(new MessageRouterStub());
     var eventStore = new RavenEventStore(eventPublisher, "RavenDB");
     eventStore.DeleteCollection();
     var events = new List<IDomainEvent>
                      {
                          new ValidEvent(id),
                          new AnotherValidEvent(id),
                          new ValidEvent(id),
                          new AnotherValidEvent(id)
                      };
     eventStore.InsertBatchTest(events);
     var eventsFromStore = eventStore.GetEventsTest(id);
     foreach (var domainEvent in eventsFromStore)
     {
         events.Should().Contain(domainEvent);
     }
     
 }
Beispiel #25
0
        public async Task InMemoryEventBus_Configuration_RetryStrategy_WhenDispatchParallel()
        {
            bool callbackCalled = false;
            var  cfgBuilder     =
                new InMemoryEventBusConfigurationBuilder()
                .SetRetryStrategy(100, 3)
                .DefineErrorCallback((e, ctx) => callbackCalled = true)
                .AllowParallelDispatchFor <ParallelEvent>();

            var b = new InMemoryEventBus(cfgBuilder.Build());

            var evt = new ParallelEvent()
            {
                RetryMode = true
            };

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            callbackCalled.Should().BeFalse();
            evt.ThreadsInfos.Should().HaveCount(2);
        }
Beispiel #26
0
        public AzureServiceBusServer(string emiter, ILoggerFactory loggerFactory,
                                     AzureServiceBusServerConfiguration configuration, InMemoryEventBus inMemoryEventBus = null)
        {
            if (string.IsNullOrWhiteSpace(emiter))
            {
                throw new ArgumentNullException(nameof(emiter));
            }
            if (loggerFactory == null)
            {
                loggerFactory = new LoggerFactory();
                loggerFactory.AddProvider(new DebugLoggerProvider());
            }
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

            _emiter = emiter;
            _logger = loggerFactory.CreateLogger <AzureServiceBusServer>();

            _client = new QueueClient(configuration.ConnectionString, configuration.QueueConfiguration.QueueName);
            _client.RegisterMessageHandler(ReceiveMessageAsync, ReceiveMessageExceptionAsync);
            _inMemoryEventBus = inMemoryEventBus;
        }
Beispiel #27
0
        public async Task InMemoryEventBus_PublishEventAsync_TransactionnalEvent()
        {
            TransactionEventHandler.DataParsed = string.Empty;

            var evt = new TransactionEvent(
                new Event1 {
                Data = "Data1"
            },
                new Event2 {
                Data = "Data2"
            },
                new Event3 {
                Data = "Data3"
            }
                );

            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(evt).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TransactionEventHandler.DataParsed.Should().Be("|1:Data1|2:Data2|3:Data3");
        }
Beispiel #28
0
        public async Task InMemoryEventBus_Configuration_DispatchIfClause()
        {
            TestIfEventHandler.ResetData();
            var cfgBuilder =
                new InMemoryEventBusConfigurationBuilder()
                .DispatchOnlyIf <TestIfEvent>(e => e.Data > 1);

            var b = new InMemoryEventBus(cfgBuilder.Build());

            TestIfEventHandler.Data.Should().Be(0);

            (await b.PublishEventAsync(new TestIfEvent {
                Data = 1
            }).ConfigureAwait(false)).IsSuccess.Should().BeFalse();

            TestIfEventHandler.Data.Should().Be(0);

            (await b.PublishEventAsync(new TestIfEvent {
                Data = 10
            }).ConfigureAwait(false)).IsSuccess.Should().BeTrue();

            TestIfEventHandler.Data.Should().Be(10);
        }
Beispiel #29
0
        /// <summary>
        /// Configure the bootstrapper to use InMemory buses for dispatching events.
        /// </summary>
        /// <param name="bootstrapper">Instance of boostrapper.</param>
        /// <param name="configuration">Configuration to use for in memory event bus.</param>
        /// <param name="excludedEventsDLLs">DLLs name to exclude from auto-configuration into IoC
        /// (IAutoRegisterType will be ineffective).</param>
        public static Bootstrapper UseInMemoryEventBus(this Bootstrapper bootstrapper, InMemoryEventBusConfiguration configuration = null, params string[] excludedEventsDLLs)
        {
            var service = InMemoryBusesBootstrappService.Instance;

            service.BootstrappAction += (ctx) =>
            {
                InMemoryEventBus.InitHandlersCollection(excludedEventsDLLs);
                if (ctx.IsServiceRegistered(BootstrapperServiceType.IoC))
                {
                    bootstrapper.AddIoCRegistration(new TypeRegistration(typeof(InMemoryEventBus), typeof(IDomainEventBus), typeof(InMemoryEventBus)));
                    if (configuration != null)
                    {
                        bootstrapper.AddIoCRegistration(new InstanceTypeRegistration(configuration, typeof(InMemoryEventBusConfiguration)));
                    }
                }
                bootstrapper.AddNotifications(PerformEventChecksAccordingToBootstrapperParameters(ctx, configuration));
            };
            if (!bootstrapper.RegisteredServices.Any(s => s == service))
            {
                bootstrapper.AddService(service);
            }
            return(bootstrapper);
        }
Beispiel #30
0
        public async Task CanPublishUsingInMemoryBus()
        {
            //arrange
            var eventHandlerFactory = new DefaultEventHandlerFactory();
            var eventBus            = new InMemoryEventBus(eventHandlerFactory);
            var eventPublisher      = new EventPublisher(eventBus);
            var eventHandler        = new CustomEventHandler();

            eventHandlerFactory.RegisterHandler(eventHandler);

            var evt = new CustomEvent("Test message");

            //act
            await eventPublisher.PublishAsync(evt).ConfigureAwait(false);

            //Wait for events to propagate/tasks to finish
            await Task.Delay(100).ConfigureAwait(false);

            //assert
            Assert.Single(eventHandler.Events);
            Assert.Equal(evt.Id, eventHandler.Events[0].Id);
            Assert.Equal(evt.EventId, eventHandler.Events[0].EventId);
            Assert.Equal(evt.Message, eventHandler.Events[0].Message);
        }
 public async Task PublishSingleEvent()
 {
     var bus = new InMemoryEventBus();
     await bus.PublishEventAsync(new TestDispatchEvent(0, MillisecondsJobDuration != 0, MillisecondsJobDuration));
 }
 public void GlobalSetupA()
 {
     InMemoryEventBus.InitHandlersCollection(new string[0]);
 }
Beispiel #33
0
        public void All_The_Events_Should_Be_Returned_In_The_Right_Order()
        {
            var eventBus = new InMemoryEventBus(new MessageRouterStub());
            var eventStore = new StubEventStore(eventBus);
            var events = new List<IDomainEvent>();
            events.Add(new ValidEvent(Guid.Empty) { EventNumber = 0 });
            events.Add(new AnotherValidEvent(Guid.Empty) { EventNumber = 1 });
            events.Add(new ValidEvent(Guid.Empty) { EventNumber = 2 });
            events.Add(new AnotherValidEvent(Guid.Empty) { EventNumber = 3 });
            eventStore.InsertEvents(events);

            var retrievedEvents = eventStore.GetAllEvents();

            Assert.AreEqual(4, retrievedEvents.Count());
            for(var count = 0; count < 4; count++)
            {
                var @event = retrievedEvents.ElementAt(count);
                Assert.AreEqual(count, @event.EventNumber);
                if(count % 2== 0)
                    Assert.IsInstanceOf<ValidEvent>(@event);
                else
                {
                    Assert.IsInstanceOf<AnotherValidEvent>(@event);
                }
            }
        }
Beispiel #34
0
 protected override void Given()
 {
     var stubUnitOfWork = new InMemoryEventBus(new MessageRouterStub());
     var eventStore = new StubEventStore(stubUnitOfWork);
     _aggregate = eventStore.Get<StubAggregate>(Guid.Empty);
 }
Beispiel #35
0
        public async Task PublishEventAsync_Should_ResultFail_ShouldBeReturned()
        {
            var b = new InMemoryEventBus();

            (await b.PublishEventAsync(new TestResultFailedEvent(), null).ConfigureAwait(false)).IsSuccess.Should().BeFalse();
        }
Beispiel #36
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.LoginPath    = "/Login";
                options.ClaimsIssuer = "webills.com";
            });

            services.AddControllers(options =>
            {
                options.Filters.Add(new AuthorizeFilter());
            });

            services.AddRazorPages(config =>
            {
                config.RootDirectory = "/";
                config.Conventions.AddPageRoute("/Home/Dashboard", "");
                config.Conventions.Add(new CustomPageRouteModelConvention());
            })
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
                options.Conventions.ConfigureFilter(new AuthorizeFilter());
            })
            .AddMvcOptions(options =>
            {
                options.Filters.Add <ExceptionsFilter>();
            })
            .AddRazorRuntimeCompilation();

            services.AddSingleton <IAuthService, AuthService>();

            var emailHost = Environment.GetEnvironmentVariable("email_host", EnvironmentVariableTarget.User) ?? "";
            var port      = Environment.GetEnvironmentVariable("email_port", EnvironmentVariableTarget.User) ?? "0";
            var user      = Environment.GetEnvironmentVariable("email_user", EnvironmentVariableTarget.User) ?? "";
            var password  = Environment.GetEnvironmentVariable("email_password", EnvironmentVariableTarget.User) ?? "";

            var eventBus = new InMemoryEventBus();

            services.AddSingleton <IEventBus>(eventBus);

            services.AddNotificationsModule(new Notification.Module.Configurations
            {
                DataConnectionString = this.Configuration.GetConnectionString("dataConnection")
            }, new Notification.Module.EventsToSubscribe(nameof(UserAccount.CreateNewAccount.AccountCreated)), eventBus);

            services.AddUserAccountModule(new UserAccount.Module.Configurations
            {
                DefaultAccount = new UserAccount.Module.Configurations.DefaultUserAccount
                {
                    Name     = "Admin",
                    Password = "******",
                    Email    = "*****@*****.**",
                },
                DataConnectionString = this.Configuration.GetConnectionString("dataConnection")
            }, eventBus);

            services.AddSingleton(provider =>
            {
                return(new FinancialControl.Module(new Webills.FinancialControl.Configurations
                {
                    DataConnectionString = this.Configuration.GetConnectionString("dataConnection")
                }));
            });
        }
Beispiel #37
0
 public InMemoryEventBus_Tests()
 {
     InMemoryEventBus.InitHandlersCollection(new string[0]);
     CleanRegistrationInDispatcher();
 }