コード例 #1
0
ファイル: Program.cs プロジェクト: mishrsud/Ximo
        private static IServiceProvider Bootstrap()
        {
            IServiceCollection serviceCollection = new ServiceCollection();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json", false, true);
            IConfiguration configuration = builder.Build();

            serviceCollection.AddSingleton(configuration);

            serviceCollection.AddLogging();

            serviceCollection.RegisterDefaultCommandBus();
            serviceCollection.RegisterDefaulDomainEventBus();
            serviceCollection.RegisterDefaultQueryProcessor();

            serviceCollection.LoadModule <DomainModule>();
            serviceCollection.LoadModule <DomainDataModule>(configuration);
            serviceCollection.LoadModule <ReadModelModule>(configuration);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            serviceProvider.GetService <ILoggerFactory>().AddConsole();

            var domainEventBus = serviceProvider.GetRequiredService <IDomainEventBus>();

            DomainModule.RegisterSubscriptions(domainEventBus);
            ReadModelModule.RegisterSubscriptions(domainEventBus);

            return(serviceProvider);
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: inshapardaz/desktop-client
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            app.Use(async(context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404 &&
                    !Path.HasExtension(context.Request.Path.Value) &&
                    !context.Request.Path.Value.StartsWith("/api"))
                {
                    context.Request.Path = "/";
                    await next();
                }
            });

            Console.WriteLine("Starting database migration");
            DomainModule.UpdateDatabase(new UserSettings());
            Console.WriteLine("Database migration finished");

            Console.WriteLine("Starting job server");
            GlobalConfiguration.Configuration.UseMemoryStorage();
            app.UseHangfireDashboard();
            app.UseHangfireServer();

            Console.WriteLine("Starting api server");
            app.UseCors(policy => policy.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            app.UseMvc();
            Console.WriteLine("Application ready");
        }
コード例 #3
0
        public static void Register(IServiceCollection service)
        {
            service.AddTransient <ICountryService, CountryService>();
            service.AddTransient <ICityService, CityService>();

            DomainModule.Register(service);
        }
コード例 #4
0
ファイル: IoC.cs プロジェクト: poferrari/estudo-kafka
 public static IServiceCollection ConfigureContainer(this IServiceCollection services, IConfiguration configuration)
 {
     DataModule.Register(services, configuration);
     DomainModule.Register(services);
     InfrastructureModule.Register(services, configuration);
     return(services);
 }
コード例 #5
0
 public static void RegisterModules(IServiceCollection services)
 {
     AuthenticateModule.Register(services);
     DomainModule.RegisterModules(services);
     TestLusherModule.RegisterModules(services);
     PsychoBioTestModule.RegisterModules(services);
     InfrastructureModule.RegisterModules(services);
 }
コード例 #6
0
        /// <summary>
        /// Configures the service container.
        /// </summary>
        /// <param name="services">The service container.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();

            // Enabled CORS to allow access from browser applications on different domains.
            services.AddCors();

            // Configure the API and JSON behaviour.
            services.AddMvc(options =>
            {
                options.InputFormatters.RemoveType <JsonPatchInputFormatter>();
                options.OutputFormatters.RemoveType <StringOutputFormatter>();
                options.Filters.Add(new ParameterValidationFilter());
                options.Filters.Add(new ModelStateValidationFilter());
                options.Filters.Add(new EntityNotFoundExceptionFilter());
                options.Filters.Add(new InvalidTradeExceptionFilter());
                options.Filters.Add(new ValidationExceptionFilter());
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.Converters.Add(new OnlyDateConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            // Configure JWT authentication.
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = JwtSettings.SecurtyKey,
                    ValidIssuer    = JwtSettings.Issuer,
                    ValidAudiences = new[] { JwtSettings.InvestorAudience, JwtSettings.AdministratorAudience }
                };
            });

            // Configure Authorization to prevent investor users from using admin features.
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    AuthorizationPolicies.Administrators,
                    policy => policy.RequireClaim(JwtRegisteredClaimNames.Aud, JwtSettings.AdministratorAudience));
            });

            // Enable Swagger and Swagger UI to make exploration of the API easier.
            services.AddSwaggerGen(SwaggerConfig.Configure);

            // Register the components from all modules in the dependency injection container.
            DomainModule.ConfigureServices(services);
            RepositoriesModule.ConfigureServices(services);
            AsxModule.ConfigureServices(services);
            YahooModule.ConfigureServices(services);
        }
コード例 #7
0
        public WorkerParseData(string domain) : base(RabbitMQManager.GetRabbitMQServer(ConfigStatic.KeyRabbitMqCrlProductProperties),
                                                     ConfigStatic.GetQueueParse(domain), false)
        {
            var domainModule = new DomainModule();
            var kernel       = new StandardKernel(domainModule);

            _handlerParserProperties = kernel.Get <IHandlerParserProperties>();
            _handlerParserProperties.Init(domain);
        }
コード例 #8
0
        public WorkerDownloadHtml(string domain) : base(
                RabbitMQManager.GetRabbitMQServer(ConfigStatic.KeyRabbitMqCrlProductProperties),
                ConfigStatic.GetQueueWaitDownloadHtml(domain), false)
        {
            var domainModule = new DomainModule();
            var kernel       = new StandardKernel(domainModule);

            _h1 = kernel.Get <HandlerDownloadHtml>();
            _h1.Init(domain);
        }
コード例 #9
0
ファイル: Startup.cs プロジェクト: JacobSnover/CookItBook
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            DM = new DomainModule(services);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: inshapardaz/desktop-client
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(provider => Configuration);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();
            services.AddSingleton <IUrlHelperFactory, UrlHelperFactory>();
            services.AddSingleton <IProvideUserSettings, UserSettings>();
            services.AddTransient <IApiClient, ApiClient>();

            services.AddHangfire(c => c.UseMemoryStorage());
            DomainModule.RegisterDatabases(services, new UserSettings());
            RegisterRenderers(services);

            if (UseOffline)
            {
                DatabaseClientModule.RegisterDatabases(services, new UserSettings());

                services.AddBrighter()
                .AsyncHandlersFromAssemblies(
                    typeof(Startup).GetTypeInfo().Assembly,
                    typeof(DomainModule).GetTypeInfo().Assembly);
                services.AddDarker()
                .AddHandlersFromAssemblies(
                    typeof(DatabaseClientModule).GetTypeInfo().Assembly,
                    typeof(DomainModule).GetTypeInfo().Assembly
                    );

                Mapper.Initialize(c =>
                {
                    c.AddProfile(new MappingProfile());
                    c.AddProfile(new DatabaseClientMappings());
                }
                                  );
            }
            else
            {
                services.AddBrighter()
                .AsyncHandlersFromAssemblies(
                    typeof(Startup).GetTypeInfo().Assembly,
                    typeof(ApiClientModule).GetTypeInfo().Assembly,
                    typeof(DomainModule).GetTypeInfo().Assembly);
                services.AddDarker()
                .AddHandlersFromAssemblies(
                    typeof(DomainModule).GetTypeInfo().Assembly,
                    typeof(ApiClientModule).GetTypeInfo().Assembly);

                Mapper.Initialize(c => c.AddProfile(new MappingProfile()));
            }

            Mapper.AssertConfigurationIsValid();
        }
コード例 #11
0
        private void Init()
        {
            _servicesCollection = new ServiceCollection();

            // mock with memory database
            _servicesCollection.AddDbContext <MyExpensesContext>(options => options.UseInMemoryDatabase(Guid.NewGuid().ToString()));

            // configure all others projects
            DomainModule.ConfigureServices(_servicesCollection);
            InfrastructureModule.ConfigureServices(_servicesCollection);

            // build
            _serviceProvider = _servicesCollection.BuildServiceProvider();
        }
コード例 #12
0
 public void Add(DomainModule.StorageOut si)
 {
     try
     {
         NHinbernateSessionFactory.OpenSession();
         StorageOutDao.Save(si);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         NHinbernateSessionFactory.Commit();
     }
 }
コード例 #13
0
        public void Add(DomainModule.Category c)
        {
            try
            {
                NHinbernateSessionFactory.OpenSession();
            CategoryDao.Save(c);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                NHinbernateSessionFactory.Commit();
            }
        }
コード例 #14
0
        public void Add(DomainModule.ProductInfo product)
        {
            try
            {
                NHinbernateSessionFactory.OpenSession();

                ProductDao.Save(product);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                NHinbernateSessionFactory.Commit();
            }
        }
コード例 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(options =>
                                    options.Filters.Add(new HttpResponseUserFriendlyExceptionFilter()));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Potential Clients API", Version = "v1"
                });
            });

            services.AddDbContext <PotentialClientsContext>(options =>
                                                            options.UseSqlServer(Configuration.GetConnectionString("PotentialClientsContext")));

            DomainModule.ConfigureServices(services);
            EFCoreModule.ConfigureServices(services);
        }
コード例 #16
0
 public void Add(DomainModule.StorageOut si, IList<StorageOutItem> list)
 {
     try
     {
         NHinbernateSessionFactory.OpenSession();
         si.Warehouse = WarehouseDao.GetWarehouseByUser(si.User.Id);
         StorageOutDao.Save(si);
         for (int i = 0; i < list.Count; i++)
         {
             list[i].List = si;
             StorageOutItemDao.Save(list[i]);
             WarehouseItem witem = WarehouseItemDao.GetBySpecId(si.Warehouse.Id, list[i].Specification.Id);
             if (witem == null)
             {
                 witem = new WarehouseItem();
                 witem.Warehouse = si.Warehouse;
                 witem.Specification = list[i].Specification;
                 witem.Amount = 0;
             }
             witem.Amount -= list[i].Amount;
             WarehouseItemDao.SaveOrUpdate(witem);
         }
     }
     catch (NHibernate.HibernateException hex)
     {
         NHinbernateSessionFactory.Rollback();
         throw hex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         NHinbernateSessionFactory.Commit();
     }
 }
コード例 #17
0
        /// <summary>
        /// Configures the application.
        /// </summary>
        /// <param name="app">The application builder instance.</param>
        /// <param name="env">The hosting environment.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseAuthentication();

            // Enabled CORS to allow access from browser applications on different domains.
            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            app.UseMvc();

            // Enable Swagger and Swagger UI to make exploration of the API easier.
            app.UseSwagger();
            app.UseSwaggerUI(SwaggerConfig.ConfigureUI);
            app.UseSwaggerBearerAuthorization();

            // Start the leader board re-calculation timer.
            DomainModule.StartTimer(app.ApplicationServices);
        }
コード例 #18
0
 public void Update(DomainModule.StorageIn si)
 {
     try
     {
         NHinbernateSessionFactory.OpenSession();
         StorageInDao.Update(si);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         NHinbernateSessionFactory.Commit();
     }
 }
コード例 #19
0
        private static void Main()
        {
            using (var container = new Container())
            {
                container.Options.AllowResolvingFuncFactories();
                // configuration appsettings convention
                IConfiguration configuration = new ConfigurationBuilder()

                                               .SetBasePath(Directory.GetCurrentDirectory())
                                               .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
                                               .AddEnvironmentVariables()
                                               .Build();
                container.Options.RegisterParameterConvention(new AppSettingsConvention(key => configuration[key]));

                ILoggerFactory loggerFactory = new LoggerFactory()
                                               .AddConsole()
                                               .AddDebug();

                container.Options.DependencyInjectionBehavior = new MsContextualLoggerInjectionBehavior(loggerFactory, container);

                ILogger logger = loggerFactory.CreateLogger <Program>();
                //container.RegisterSingleton<ILogger>(logger);
                logger.LogInformation("Starting BC 'KmStanden' host...");

                ExampleCQRS.Infrastructure.Registrations.InfrastructureModule.RegisterEventBus(container, configuration);

                DomainModule.RegisterAll(container);
                ApplicationModule.RegisterAll(container);
                InfrastructureModule.RegisterAll(container);
                InfrastructureModule.RegisterEventForwarder(container);
                RabbitMqModule.RegisterCommandConsumers(container);

                var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(new Uri(configuration["CommandBusConnection"]), hst =>
                    {
                        hst.Username(configuration["CommandBusUserName"]);
                        hst.Password(configuration["CommandPassword"]);
                    });

                    cfg.SeparatePublishFromSendTopology();
                    // command queue
                    cfg.ReceiveEndpoint(host,
                                        RabbitMqConstants.CommandsQueue, e =>
                    {
                        e.LoadFrom(container);
                    });
                });

                container.RegisterSingleton(bus);

                //container.RegisterSingleton(RabbitMqConfiguration.ConfigureBus((cfg, host) =>
                //{
                //    cfg.SeparatePublishFromSendTopology();
                //    // command queue
                //    cfg.ReceiveEndpoint(host,
                //        RabbitMqConstants.CommandsQueue, e =>
                //        {
                //            e.LoadFrom(container);
                //        });
                //}));

                using (var eventBus = container.GetInstance <IIntegrationEventBus>())
                {
                    var cbus = container.GetInstance <IBusControl>();

                    cbus.StartAsync();

                    Console.WriteLine("Listening for commands.. Press enter to exit");
                    Console.ReadLine();

                    cbus.StopAsync();
                }
            }
        }
コード例 #20
0
 public void Update(DomainModule.StorageOut si, IList<StorageOutItem> list)
 {
     throw new NotImplementedException();
 }
コード例 #21
0
 public static void RegisterServices(IServiceCollection services)
 {
     ApplicationModule.RegisterServices(services);
     DomainModule.RegisterServices(services);
 }
コード例 #22
0
        private static void Main()
        {
            using (var container = new Container())
            {
                container.Options.AllowResolvingFuncFactories();
                // configuration appsettings convention
                IConfiguration config = new ConfigurationBuilder()
                                        .SetBasePath(Directory.GetCurrentDirectory())
                                        .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
                                        .AddEnvironmentVariables()
                                        .Build();
                container.Options.RegisterParameterConvention(new AppSettingsConvention(key => config[key]));

                ILoggerFactory loggerFactory = new LoggerFactory()
                                               .AddConsole()
                                               .AddDebug();
                container.Options.DependencyInjectionBehavior = new MsContextualLoggerInjectionBehavior(loggerFactory, container);

                ILogger logger = loggerFactory.CreateLogger <Program>();
                //container.RegisterSingleton<ILogger>(logger);
                logger.LogInformation("Starting BC 'Ritten' host...");

                ExampleCQRS.Infrastructure.Registrations.InfrastructureModule.RegisterEventBus(container, config);

                DomainModule.RegisterAll(container);
                ApplicationModule.RegisterAll(container);
                InfrastructureModule.RegisterAll(container);
                InfrastructureModule.RegisterEventForwarder(container);
                RabbitMqModule.RegisterCommandConsumers(container);
                RabbitMqModule.RegisterEventConsumers(container);

                //ReadModel.Infrastructure.Registrations.InfrastructureModule.RegisterAll(container);

                container.RegisterSingleton(RabbitMqConfiguration.ConfigureBus((cfg, host) =>
                {
                    // command queue
                    //cfg.ReceiveEndpoint(host,
                    //    RabbitMqConstants.CommandsQueue, e =>
                    //    {
                    //        e.Handler<ICommand>(context =>
                    //        Console.Out.WriteLineAsync($"Command received : {context.Message.GetType()}"));
                    //        //e.LoadFrom(container);// TODO: prevent receiving same events
                    //    });
                    // events queue
                    cfg.ReceiveEndpoint(host, RabbitMqConstants.GetEventsQueue(BoundedContextName), e =>
                    {
                        e.Handler <IDomainEvent>(context =>
                                                 Console.Out.WriteLineAsync($"Event received : {context.Message.GetType()}"));
                        e.LoadFrom(container);
                    });
                }));

                EventMappings.Configure();

                var eventBus = container.GetInstance <IIntegrationEventBus>();
                eventBus.Subscribe <KmStandCreated, RitService>();

                //var bus = container.GetInstance<IBusControl>();

                //bus.StartAsync();

                Console.WriteLine("Listening for commands.. Press enter to exit");
                Console.ReadLine();

                //bus.StopAsync();
            }
        }