Example #1
0
        public void RegisteredMappersAreCreated()
        {
            sut = new MapperFactory(new TestMappingProfile1(), new TestMappingProfile2());

            IMapper <Class1, Class2> mapper1 = sut.Create <Class1, Class2>();
            IMapper <Class2, Class1> mapper2 = sut.Create <Class2, Class1>();

            Assert.IsNotNull(mapper1);
            Assert.IsNotNull(mapper2);
            Assert.IsInstanceOfType(mapper1, typeof(TestMappingProfile1.Mapper));
            Assert.IsInstanceOfType(mapper2, typeof(TestMappingProfile2.Mapper));
        }
        public GetAllTests()
        {
            var context = ProductCatalogContextFactory.Create();
            var mapper  = MapperFactory.Create();

            _handler = new GetAllQueryHandler(context, mapper);
        }
Example #3
0
        public UpdateProductTests()
        {
            _context = ProductCatalogContextFactory.Create();
            var mapper = MapperFactory.Create();

            _handler = new UpdateProductHandler(_context, mapper);
        }
        public GetByCodeTests()
        {
            var context    = ProductCatalogContextFactory.Create();
            var mapper     = MapperFactory.Create();
            var loggerMock = new Mock <ILogger <GetByCodeQueryHandler> >();

            _handler = new GetByCodeQueryHandler(context, mapper, loggerMock.Object);
        }
        public static void Configure(IServiceCollection services)
        {
            services.AddScoped <IDbConnectionFactory, CallDbConnectionFactory>();
            services.AddScoped(typeof(IBaseRepository <>), typeof(BaseRepository <>));
            services.AddScoped <IBaseService <CallDto>, BaseService <CallDto, Call> >();

            services.AddSingleton(_ => MapperFactory.Create());
        }
        public static void Configure(IServiceCollection services)
        {
            services.AddScoped <ApiClient>();
            services.AddScoped <IHitbtcTradeClient, HitbtcTradeClient>();
            services.AddScoped <IConnectionFactory, SqlServerConnectionFactory>();
            services.AddScoped <IUnitOfWorkFactory, UnitOfWorkFactory>();
            services.AddScoped(typeof(IBaseRepository <>), typeof(BaseRepository <>));
            services.AddScoped <TradeService>();

            services.AddSingleton(sp => MapperFactory.Create());
        }
Example #7
0
        public void SetUp()
        {
            _mapper            = MapperFactory.Create();
            _databaseMock      = new DatabaseMock <SessionDao>();
            _sessionRepoMock   = new SessionRepositoryMock();
            _timeEntryRepoMock = new TimeEntryRepositoryMock();

            _sessionSvc = new SessionService(
                _mapper,
                _sessionRepoMock.Object,
                _timeEntryRepoMock.Object
                );
        }
Example #8
0
        public void WhenNotNullableType_ShouldNotProtectAgainstNulls()
        {
            // Arrange
            var definition = _fixture.Create <Definition>();

            definition.Columns.Add("test", typeof(int));
            var sut = new MapperFactory();

            // Act
            var actual = sut.Create(definition);

            // Assert
            var code = actual.NormalizeWhitespace().ToString();

            code.Should().Contain("test.ToInt();");
        }
        public void Initialize(Type concreteType, IGenericMapperConfiguration config)
        {
            // Get JSON accessor
            var jsonColumn = typeof(IGenericColumns).GetProperty(config.JsonColumn);

            JsonAccessor = ReflectionTool.PropertyAccessor <IGenericColumns, string>(jsonColumn);

            var baseProperties = typeof(TBase).GetProperties()
                                 .Select(p => p.Name);
            var configuredProperties = config.PropertyConfigs.Select(cm => cm.PropertyName);
            var ignoredProperties    = baseProperties.Concat(configuredProperties).ToArray();

            _jsonSettings = JsonSettings.Minimal
                            .Overwrite(j => j.ContractResolver = new DifferentialContractResolver <TReference>(ignoredProperties));

            _configuredMappers = config.PropertyConfigs.Select(pc => MapperFactory.Create(pc, concreteType)).ToArray();
        }
        public async Task GetValue_NoParameters_ShouldReturnValue()
        {
            // Arrange
            var database      = DatabaseFactory.CreateContext();
            var mapper        = MapperFactory.Create();
            var simpleService = new SimpleService(database, mapper);

            database.TestModels.Add(new TestModel {
                Id = 1, Name = "value"
            });
            database.SaveChanges();

            // Act
            var result = await simpleService.GetValue();

            // Assert
            Assert.Equal("value", result.Name);
        }
        public void Create_DtoUser_To_UserAppModel_Mappert_Test()
        {
            #region === ARRANGE ===

            MapperFactory mapperFactory = new MapperFactory();

            #endregion

            #region === ACT ===

            var mapper = mapperFactory.Create <DtoUser, UserAppModel>();

            #endregion

            #region === ASSERT ===

            Assert.IsInstanceOfType(mapper, typeof(AbstractMapper <DtoUser, UserAppModel>));

            #endregion
        }
 public ShowTimeServiceTest()
 {
     _mockMovieTheaterRepository = new Mock<IRepository<MovieTheater, int>>();
     _mockShowTimeTheaterRepository = new Mock<IRepository<ShowTime, int>>();
     _mapper = MapperFactory.Create();
 }
Example #13
0
 public TheaterServiceTest()
 {
     _mockTheaterRepository = new Mock <IRepository <Theater, int> >();
     _mapper = MapperFactory.Create();
 }
Example #14
0
 public EmployeeService(IEmployeeRepository repo)
     : base(MapperFactory.Create <EmployeeProfile>())
     => this.repo = repo;
Example #15
0
        public static ModuleOptions AddCountriesModule(
            this ModuleOptions options)
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.AddTag("countries");

            // enqueue data and do nothing === MOVED TO STARTUP ===
            //options.Context.Services.AddSingleton<IQueue<CountriesExportData>>(sp => // AddQueue<T>(sp => ....)
            //{
            //    return new InMemoryQueue<CountriesExportData>(o => o
            //        .Mediator(sp.GetService<IMediator>())
            //        .Tracer(sp.GetService<ITracer>())
            //        .LoggerFactory(sp.GetService<ILoggerFactory>())
            //        .NoRetries());
            //});
            //options.Context.Services.AddSingleton<IQueue<CountriesExportData>>(sp => // AddQueue<T>(sp => ....)
            //{
            //    return new AzureServiceBusQueue<CountriesExportData>(o => o
            //        .Mediator(sp.GetService<IMediator>())
            //        .Tracer(sp.GetService<ITracer>())
            //        .LoggerFactory(sp.GetService<ILoggerFactory>())
            //        .ConnectionString(............)
            //        .NoRetries());
            //});
            // dequeue and process data
            //options.Context.Services.AddQueueProcessItemsStartupTask<CountriesExportData>(new TimeSpan(0, 0, 30));

            //options.Context.Services.AddScoped<ICountryRepository>(sp =>
            //{
            //    return new CountryRepository(
            //        new RepositoryTracingDecorator<Country>(
            //            sp.GetService<ILogger<CountryRepository>>(),
            //            sp.GetService<ITracer>(),
            //            new RepositoryLoggingDecorator<Country>(
            //                sp.GetRequiredService<ILogger<CountryRepository>>(),
            //                new RepositoryTenantDecorator<Country>(
            //                    "naos_sample_test",
            //                    new RepositoryOrderDecorator<Country>(
            //                        e => e.Name,
            //                        new InMemoryRepository<Country, DbCountry>(o => o
            //                            .LoggerFactory(sp.GetRequiredService<ILoggerFactory>())
            //                            .Mediator(sp.GetRequiredService<IMediator>())
            //                            .Context(sp.GetRequiredService<InMemoryContext<Country>>())
            //                            .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())), // singleton
            //                            e => e.Identifier))))));
            //});

            //options.Context.Services.AddSingleton(sp => new InMemoryContext<Country>(new[]
            //{
            //    new Country { Code = "de", LanguageCodes = new[] {"de-de" }, Name = "Germany", TenantId = "naos_sample_test", Id = "de" },
            //    new Country { Code = "nl", LanguageCodes = new[] {"nl-nl" }, Name = "Netherlands", TenantId = "naos_sample_test", Id = "nl" },
            //    new Country { Code = "be", LanguageCodes = new[] {"fr-be", "nl-be" }, Name = "Belgium", TenantId = "naos_sample_test", Id = "be" },
            //}.ToList()));

            options.Context.Services
            .AddScoped <IGenericRepository <Country> >(sp =>
            {
                return(new InMemoryRepository <Country, DbCountry>(o => o
                                                                   .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                   .Mediator(sp.GetRequiredService <IMediator>())
                                                                   .Context(sp.GetRequiredService <InMemoryContext <Country> >())
                                                                   .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())), // singleton
                                                                   e => e.Identifier));
            })
            .Decorate <IGenericRepository <Country>, RepositoryTracingDecorator <Country> >()
            .Decorate <IGenericRepository <Country>, RepositoryLoggingDecorator <Country> >()
            .Decorate <IGenericRepository <Country> >((inner, sp) => new RepositoryTenantDecorator <Country>("naos_sample_test", inner))
            //.Decorate<IGenericRepository<Country>>((inner, sp) => new RepositoryIncludeDecorator<Country>(c => c.State, inner))
            .Decorate <IGenericRepository <Country> >((inner, sp) => new RepositoryOrderDecorator <Country>(i => i.Name, inner))

            .AddSingleton(sp => new InMemoryContext <Country>(new[]
            {
                new Country {
                    Code = "de", LanguageCodes = new[] { "de-de" }, Name = "Germany", TenantId = "naos_sample_test", Id = "de"
                },
                new Country {
                    Code = "nl", LanguageCodes = new[] { "nl-nl" }, Name = "Netherlands", TenantId = "naos_sample_test", Id = "nl"
                },
                new Country {
                    Code = "be", LanguageCodes = new[] { "fr-be", "nl-be" }, Name = "Belgium", TenantId = "naos_sample_test", Id = "be"
                },
            }.ToList()));

            options.Context.Services.AddSeederStartupTask <Country, IGenericRepository <Country> >(new[]
            {
                new Country {
                    Code = "us", LanguageCodes = new[] { "en-us" }, Name = "United States", TenantId = "naos_sample_test", Id = "us"
                },
            }, delay: new TimeSpan(0, 0, 3));

            options.Context.Messages.Add("naos services builder: countries service added");

            return(options);
        }
 public MovieServiceTest()
 {
     _mockMovieRepository = new Mock <IRepository <Movie, int> >();
     _mockUnitOfWork      = new Mock <IUnitOfWork>();
     _mapper = MapperFactory.Create();
 }
        private static IMapper SetupMapper()
        {
            var factory = new MapperFactory();

            return(factory.Create());
        }
Example #18
0
        public static ModuleOptions AddCustomersModule(
            this ModuleOptions options,
            string section = "naos:sample:customers")
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.AddTag("customers"); // TODO: discover (how?) alle aggregates for this module
            options.Context.AddServiceClient <UserAccountsClient>();

            var configuration = options.Context.Configuration?.GetSection($"{section}:cosmosDb").Get <CosmosConfiguration>() ?? new CosmosConfiguration();

            options.Context.Services.AddScoped <ICustomerRepository>(sp =>
            {
                return(new CustomerRepository(
                           new RepositoryTracingDecorator <Customer>(
                               sp.GetService <ILogger <CustomerRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <Customer>(
                                   sp.GetRequiredService <ILogger <CustomerRepository> >(),
                                   new RepositoryTenantDecorator <Customer>(
                                       "naos_sample_test",
                                       new CosmosSqlRepository <Customer>(o => o
                                                                          .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                          .Mediator(sp.GetRequiredService <IMediator>())
                                                                          .Provider(sp.GetRequiredService <ICosmosSqlProvider <Customer> >()))))))); // v3
                                                                                                                                                     //.Provider(new CosmosDbSqlProviderV2<Customer>( // v2
                                                                                                                                                     //    logger: sp.GetRequiredService<ILogger<CosmosDbSqlProviderV2<Customer>>>(),
                                                                                                                                                     //    client: CosmosDbClientV2.Create(cosmosDbConfiguration.ServiceEndpointUri, cosmosDbConfiguration.AuthKeyOrResourceToken),
                                                                                                                                                     //    databaseId: cosmosDbConfiguration.DatabaseId,
                                                                                                                                                     //    collectionIdFactory: () => cosmosDbConfiguration.CollectionId,
                                                                                                                                                     //    partitionKeyPath: cosmosDbConfiguration.CollectionPartitionKey,
                                                                                                                                                     //    throughput: cosmosDbConfiguration.CollectionOfferThroughput,
                                                                                                                                                     //    isMasterCollection: cosmosDbConfiguration.IsMasterCollection)))))));
            }).AddScoped <ICosmosSqlProvider <Customer> >(sp =>
            {
                return(new CosmosSqlProviderV3 <Customer>(o => o
                                                          .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                          .Account(configuration.ServiceEndpointUri, configuration.AuthKeyOrResourceToken)
                                                          .Database(configuration.DatabaseId)
                                                          .PartitionKey(e => e.Region)));
            }).AddHealthChecks()
            .AddDocumentDb(s =>
            {
                s.UriEndpoint = configuration.ServiceEndpointUri;
                s.PrimaryKey  = configuration.AuthKeyOrResourceToken;
            },
                           name: $"{typeof(Customer).Name.Pluralize()}-cosmosdb");

            options.Context.Services.AddScoped <IOrderRepository>(sp =>
            {
                return(new OrderRepository(
                           new RepositoryTracingDecorator <Order>(
                               sp.GetService <ILogger <OrderRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <Order>(
                                   sp.GetRequiredService <ILogger <OrderRepository> >(),
                                   new RepositoryTenantDecorator <Order>(
                                       "naos_sample_test",
                                       new CosmosSqlRepository <Order, DtoOrder>(o => o
                                                                                 .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                                 .Mediator(sp.GetRequiredService <IMediator>())
                                                                                 .Provider(sp.GetRequiredService <ICosmosSqlProvider <DtoOrder> >())
                                                                                 .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())))))))); // v3
            }).AddScoped <ICosmosSqlProvider <DtoOrder> >(sp =>
            {
                return(new CosmosSqlProviderV3 <DtoOrder>(o => o
                                                          .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                          .Account(configuration.ServiceEndpointUri, configuration.AuthKeyOrResourceToken)
                                                          .Database(configuration.DatabaseId)
                                                          .Container(typeof(Order).Name.Pluralize().ToLower())
                                                          .PartitionKey(e => e.Location)));
            }).AddHealthChecks()
            .AddDocumentDb(s =>
            {
                s.UriEndpoint = configuration.ServiceEndpointUri;
                s.PrimaryKey  = configuration.AuthKeyOrResourceToken;
            },
                           name: $"{typeof(Order).Name.Pluralize()}-cosmosdb");

            options.Context.Services.AddSeederStartupTask <Customer, ICustomerRepository>(new[]
            {
                new Customer()
                {
                    Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b25", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Male", CustomerNumber = "AB-10010", FirstName = "John", LastName = "Doe", Region = "East"
                },
                new Customer()
                {
                    Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b26", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Female", CustomerNumber = "AB-10020", FirstName = "Lisa", LastName = "Doe", Region = "West"
                },
                new Customer()
                {
                    Id = "100fb10f-2ad4-4bd1-9b33-6410a5ce1b27", Email = "*****@*****.**", TenantId = "naos_sample_test", Gender = "Male", CustomerNumber = "AB-10030", FirstName = "Paul", LastName = "Doe", Region = "East"
                },
            }, delay: new TimeSpan(0, 0, 10));

            var queueStorageConfiguration = options.Context.Configuration?.GetSection($"{section}:queueStorage").Get <QueueStorageConfiguration>();

            options.Context.Services.AddSingleton <IQueue <Customer> >(sp =>
            {
                var queue = new AzureStorageQueue <Customer>(
                    new AzureStorageQueueOptionsBuilder()
                    .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                    .ConnectionString(queueStorageConfiguration.ConnectionString).Build());

                // for testing enqueue some items
                _ = queue.EnqueueAsync(new Customer()).Result;
                _ = queue.EnqueueAsync(new Customer()).Result;
                return(queue);
            });

            options.Context.Services.AddHealthChecks()
            .AddAzureQueueStorage(
                queueStorageConfiguration.ConnectionString,
                name: "Customers-azurequeuestorage");

            //options.Context.Services.AddSingleton<IValidator<CreateCustomerCommand>>(new CreateCustomerCommandValidator());
            options.Context.Messages.Add("naos services builder: customers service added");

            return(options);
        }
Example #19
0
        public void CannotRegisterMultipleMappersForSameTypes()
        {
            sut = new MapperFactory(new TestMappingProfile1(), new TestMappingProfile1());

            sut.Create <Class1, Class2>();
        }
Example #20
0
        public void UnregisteredMappersAreNotCreated()
        {
            sut = new MapperFactory(new TestMappingProfile2());

            sut.Create <Class1, Class2>();
        }
Example #21
0
 protected void Setup()
 {
     _mapper   = MapperFactory.Create();
     _repoMock = new TRepoMock();
 }
Example #22
0
        public static INaosBuilderContext AddMongoLogging(this INaosBuilderContext context)
        {
            EnsureArg.IsNotNull(context, nameof(context));
            EnsureArg.IsNotNull(context.Services, nameof(context.Services));

            var configuration = context.Configuration?.GetSection("naos:operations:logging:mongo").Get <MongoLoggingConfiguration>();

            if (configuration != null)
            {
                context.Services.AddMongoClient("logging", new MongoConfiguration
                {
                    ConnectionString = configuration.ConnectionString?.Replace("[DATABASENAME]", configuration.DatabaseName),
                    DatabaseName     = configuration.DatabaseName
                });

                context.Services.AddScoped <ILogEventRepository>(sp =>
                {
                    return(new MongoLogEventRepository(o => o
                                                       .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                       .MongoClient(sp.GetServices <IMongoClient>()
                                                                    .FirstOrDefault(c => c.Settings.ApplicationName == "logging")) //TODO: make nice extension to get a named mongoclient
                                                       .Mapper(new AutoMapperEntityMapper(MapperFactory.Create()))
                                                       .DatabaseName(configuration.DatabaseName)
                                                       .CollectionName(configuration.CollectionName)));
                });
                context.Messages.Add($"naos services builder: logging azure mongo repository added (collection={configuration.CollectionName})");
            }

            return(context);
        }
Example #23
0
        public static ModuleOptions AddUserAccountsModule(
            this ModuleOptions options,
            string connectionString         = null,
            string section                  = "naos:sample:userAccounts:entityFramework",
            UserAccountsDbContext dbContext = null)
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.AddTag("useraccounts");

            if (dbContext != null)
            {
                options.Context.Services.AddSingleton(dbContext); // cross wiring, warning this will be a singleton (not scoped)
            }

            var configuration = options.Context.Configuration?.GetSection(section).Get <EntityFrameworkConfiguration>();

            options.Context.Services.AddScoped <IGenericRepository <UserAccount> >(sp =>
            {
                return(new UserAccountRepository(
                           new RepositoryTracingDecorator <UserAccount>(
                               sp.GetService <ILogger <UserAccountRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <UserAccount>(
                                   sp.GetRequiredService <ILogger <UserAccountRepository> >(),
                                   //new RepositoryTenantDecorator<UserAccount>(
                                   //"naos_sample_test", // TODO: resolve from runtime context
                                   //new RepositorySoftDeleteDecorator<UserAccount>(
                                   new EntityFrameworkRepository <UserAccount>(o => o
                                                                               .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                               .Mediator(sp.GetRequiredService <IMediator>())
                                                                               .DbContext(sp.GetRequiredService <UserAccountsDbContext>()))))));
            });

            options.Context.Services.AddScoped <IGenericRepository <UserVisit> >(sp =>
            {
                return(new UserVisitRepository(
                           new RepositoryTracingDecorator <UserVisit>(
                               sp.GetService <ILogger <UserVisitRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <UserVisit>(
                                   sp.GetRequiredService <ILogger <UserVisitRepository> >(),
                                   new RepositoryTenantDecorator <UserVisit>(
                                       "naos_sample_test", // TODO: resolve from runtime context
                                       new RepositoryStateSoftDeleteDecorator <UserVisit>(
                                           new EntityFrameworkRepository <UserVisit>(o => o
                                                                                     .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                                     .Mediator(sp.GetRequiredService <IMediator>())
                                                                                     .DbContext(sp.GetRequiredService <UserAccountsDbContext>())
                                                                                     .Mapper(new AutoMapperEntityMapper(MapperFactory.Create())))))))));
            });

            options.Context.Services.AddDbContext <UserAccountsDbContext>(o => o
                                                                          //.UseSqlServer("Server=127.0.0.1;Database=naos_sample;User=sa;Password=Abcd1234!;Trusted_Connection=False;MultipleActiveResultSets=True;", o => o // docker
                                                                          //.UseSqlServer(configuration.ConnectionString.EmptyToNull() ?? $"Server=(localdb)\\mssqllocaldb;Database={nameof(UserAccountsDbContext)};Trusted_Connection=True;MultipleActiveResultSets=True;", o => o
                                                                          .UseSqlServer(configuration.ConnectionString, o => o
                                                                                        .MigrationsHistoryTable("__MigrationsHistory", "useraccounts")
                                                                                        .EnableRetryOnFailure())
                                                                          .UseLoggerFactory(options.Context.Services.BuildServiceProvider().GetRequiredService <ILoggerFactory>())
                                                                          //.ConfigureWarnings(w => w.Throw(RelationalEventId.QueryClientEvaluationWarning))
                                                                          .EnableSensitiveDataLogging()
                                                                          .EnableDetailedErrors());

            options.Context.Services.AddStartupTask <ApplyPendingMigrationsTask <UserAccountsDbContext> >();
            options.Context.Services.AddStartupTask <EchoStartupTask>(new TimeSpan(0, 0, 3));
            options.Context.Services.AddSeederStartupTask <UserAccountsDbContext, UserAccount>(new[]
            {
                new UserAccount()
                {
                    Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b25"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\admin"), Status = UserAccountStatus.Active
                },
                new UserAccount()
                {
                    Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b26"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\test26"), Status = UserAccountStatus.Active
                },
                new UserAccount()
                {
                    Id = Guid.Parse("100fb10f-2ad4-4bd1-9b33-6410a5ce7b27"), Email = "*****@*****.**", TenantId = "naos_sample_test", AdAccount = AdAccount.For("East\\test27"), Status = UserAccountStatus.Active
                },
            }, delay: new TimeSpan(0, 0, 10));
            //options.Context.Services.AddStartupTask(sp =>
            //    new SeederStartupTask(
            //        sp.GetRequiredService<ILoggerFactory>(),
            //        sp.CreateScope().ServiceProvider.GetService(typeof(IGenericRepository<UserAccount>)) as IGenericRepository<UserAccount>));

            options.Context.Services.AddHealthChecks()
            .AddSqlServer(configuration.ConnectionString, name: "UserAccounts-sqlserver");

            options.Context.Services.AddHealthChecks() // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-3.1#entity-framework-core-dbcontext-probe
            .AddDbContextCheck <UserAccountsDbContext>(name: "UserAccounts-dbcontext");

            options.Context.Messages.Add("naos services builder: useraccounts service added");

            return(options);
        }
Example #24
0
        public static ModuleOptions AddInventoryModule(
            this ModuleOptions options,
            string section = "naos:sample:inventory")
        {
            EnsureArg.IsNotNull(options, nameof(options));
            EnsureArg.IsNotNull(options.Context, nameof(options.Context));

            options.Context.AddTag("inventory");

            var configuration = options.Context.Configuration?.GetSection($"{section}:mongo").Get <MongoConfiguration>() ?? new MongoConfiguration();

            options.Context.Services.AddMongoClient("inventory", configuration);
            options.Context.Services.AddScoped <IInventoryRepository>(sp =>
            {
                return(new InventoryRepository(
                           new RepositoryTracingDecorator <ProductInventory>(
                               sp.GetService <ILogger <InventoryRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <ProductInventory>(
                                   sp.GetRequiredService <ILogger <InventoryRepository> >(),
                                   new MongoRepository <ProductInventory>(o => o
                                                                          //.Setup(sp, mongoConfiguration)
                                                                          .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                          .Mediator(sp.GetRequiredService <IMediator>())
                                                                          .MongoClient(sp.GetServices <IMongoClient>()
                                                                                       .FirstOrDefault(c => c.Settings.ApplicationName == "inventory")) //TODO: make nice extension to get a named mongoclient
                                                                          .DatabaseName(configuration.DatabaseName))))));
            });

            options.Context.Services.AddScoped <IReplenishmentRepository>(sp =>
            {
                return(new ReplenishmentRepository(
                           new RepositoryTracingDecorator <ProductReplenishment>(
                               sp.GetService <ILogger <ReplenishmentRepository> >(),
                               sp.GetService <ITracer>(),
                               new RepositoryLoggingDecorator <ProductReplenishment>(
                                   sp.GetRequiredService <ILogger <ReplenishmentRepository> >(),
                                   new MongoRepository <ProductReplenishment, ProductReplenishmentDocument>(o => o
                                                                                                            //.Setup(sp, mongoConfiguration)
                                                                                                            .LoggerFactory(sp.GetRequiredService <ILoggerFactory>())
                                                                                                            .Mediator(sp.GetRequiredService <IMediator>())
                                                                                                            .MongoClient(sp.GetServices <IMongoClient>()
                                                                                                                         .FirstOrDefault(c => c.Settings.ApplicationName == "inventory"))
                                                                                                            .Mapper(new AutoMapperEntityMapper(MapperFactory.Create()))
                                                                                                            .DatabaseName(configuration.DatabaseName)
                                                                                                            .CollectionName("ProductReplenishments"))))));
            });

            options.Context.Services.AddSeederStartupTask <ProductInventory, IInventoryRepository>(new[]
            {
                new ProductInventory
                {
                    Id = "548fb10e-2ad4-4bd1-9b33-6414a5ce7b10", Number = "AA1234", Quantity = 199, Region = "East"
                },
                new ProductInventory
                {
                    Id = "558fb10e-2ad4-4bd1-9b33-6414a5ce7b11", Number = "AA1234", Quantity = 188, Region = "West"
                },
                new ProductInventory
                {
                    Id = "558fb10f-2ad4-4bd1-9b33-6414a5ce7b12", Number = "BB1234", Quantity = 177, Region = "East"
                }
            }, delay: new TimeSpan(0, 0, 15));
            //options.Context.Services.AddStartupTask(sp =>
            //    new SeederStartupTask(
            //        sp.GetRequiredService<ILoggerFactory>(),
            //        sp.CreateScope().ServiceProvider.GetService(typeof(IInventoryRepository)) as IInventoryRepository));

            options.Context.Services.AddHealthChecks()
            .AddMongoDb(configuration.ConnectionString, name: "Inventory-mongodb");

            options.Context.Messages.Add("naos services builder: inventory service added");

            return(options);
        }