Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TestVisitor"/> class.
 /// </summary>
 public TestVisitor()
 {
     provider           = base.Provider.GetService <IDbProvider>();
     transactionManager = new Mock <TransactionManager>();
     option             = base.Provider.GetService <DbOption>();
     _queryBuilder      = Provider.GetService <ISqlBuilder>();
 }
Exemplo n.º 2
0
        public static SessionFactoryAndConfiguration Configure(DbOption option)
        {
            Configuration cfg = null;

            // Configurando o NHibernate usando o Fluent NHibernate.
            FluentConfiguration config = Fluently.Configure()
                                         .Database(
                MsSqlConfiguration.MsSql2008
                .ConnectionString(c => c.FromAppSetting("connectionString"))
                .ShowSql())
                                         .Cache(c => c.UseQueryCache().ProviderClass <HashtableCacheProvider>());


            foreach (var assemblyName in AppSettingsHelper.GetValue("mappingAssemblies").Split(','))
            {
                System.Console.WriteLine("carregando assembly " + assemblyName);
                config.Mappings(x => x.FluentMappings.Conventions
                                .Setup(m => m.Add(AutoImport.Never()))
                                .AddFromAssembly(Assembly.Load(assemblyName)));
            }

            config.ExposeConfiguration(cfg1 => DbCreateOrUpdate(option, cfg = cfg1));
            var sessionFactory = config.BuildSessionFactory();

            //cfg.SetListener(ListenerType.Delete, new DeleteListener());

            return(new SessionFactoryAndConfiguration(sessionFactory, cfg));
        }
Exemplo n.º 3
0
        public static DbOption SelectedDbOption()
        {
            DbConfigModel dbConfigModel = GetDbConfigModel();

            DbOption dbOption = dbConfigModel.SelectedDbOption();

            return(dbOption);
        }
Exemplo n.º 4
0
 public BaseRepository(IOptionsSnapshot <DbOption> options)
 {
     _dbOption = options.Get("JerryCms");
     if (_dbOption == null)
     {
         throw new ArgumentNullException(nameof(DbOption));
     }
     _dbConnection = ConnectionFactory.CreateConnection(_dbOption.DbType, _dbOption.ConnectionString);
 }
Exemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DbTest"/> class.
 /// </summary>
 public DbTest()
 {
     transactionManager   = new Mock <TransactionManager>();
     provider             = base.Provider.GetService <IDbProvider>();
     option               = base.Provider.GetService <DbOption>();
     _sqlBuilder          = Provider.GetService <ISqlBuilder>();
     option.IsUseParamers = false;
     ObjectConverCollection.RegistObjectConver <IRecord>(t => new Record(t.AsDictionary()));
 }
Exemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ORMVisitor"/> class.
 /// </summary>
 /// <param name="dbProvider">The db provider.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="funList">The fun list.</param>
 /// <param name="serviceProvider">The service provider.</param>
 protected ORMVisitor(IDbProvider dbProvider, DbOption dbOption, IEnumerable <IFuncVisit> funList, IServiceProvider serviceProvider = null)
 {
     _dbPrivoder          = dbProvider;
     Parameters           = new List <IDbDataParameter>();
     TableTypeDic         = new Dictionary <int, Type>();
     this.serviceProvider = serviceProvider;
     _funList             = funList;
     this.dbOption        = dbOption;
 }
Exemplo n.º 7
0
        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <param name="dbType"></param>
        /// <param name="connectionStr"></param>
        /// <returns></returns>
        public IFreeSql GetDb(string connectionStr)
        {
            DbOption dbConfig = JsonConvert.DeserializeObject <DbOption>(connectionStr);

            var freeSqlBuilder = new FreeSql.FreeSqlBuilder()
                                 .UseConnectionString(dbConfig.DbType, dbConfig.ConnectionString)
                                 .UseAutoSyncStructure(false);
            var fsql = freeSqlBuilder.Build();

            fsql.Aop.CurdBefore += CurdBefore;
            return(fsql);
        }
Exemplo n.º 8
0
        public UnitOfWork(IOptionsSnapshot <DbOption> options)
        {
            _dbOpion = options.Get("DotnetCmsOption");
            if (_dbOpion == null)
            {
                throw new ArgumentNullException(nameof(DbOption));
            }

            addEntities    = new Dictionary <object, Action>();
            updateEntities = new Dictionary <object, Action>();
            deleteEntities = new Dictionary <object, Action>();
        }
Exemplo n.º 9
0
        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbtype">数据库类型</param>
        /// <param name="ConnectionString">数据库连接字符串</param>
        /// <returns>数据库连接</returns>
        //public static IDbConnection CreateConnection()
        //{
        //    return CreateConnection(Appsettings.GetSection("DbOption").Get<DbOption>());
        //}

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        /// <param name="dbtype">数据库类型</param>
        /// <param name="ConnectionString">数据库连接字符串</param>
        /// <returns>数据库连接</returns>
        public static IDbConnection CreateConnection(DbOption dbOption)
        {
            if (dbOption.DbType.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("获取数据库连接居然不传数据库类型,你想上天吗?");
            }
            if (dbOption.ConnectionString.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException("获取数据库连接居然不传数据库类型,你想上天吗?");
            }
            Appsettings.GetSection("DbOption").Get <DbOption>();
            return(CreateConnection(dbOption.DbType, dbOption.ConnectionString));
        }
Exemplo n.º 10
0
        public DbContext(string connectionString, DbOption dbOption)
        {
            if (_sessionFactory == null)
            {
                _configuration = ConfigurationBuilder.New()
                                 .ForSql2008(connectionString)
                                 .MapEntities(GetEntityTypes());

                CreateOrUpdateDatabaseAndSchema(connectionString, dbOption);

                _sessionFactory = _configuration.BuildSessionFactory();
            }
            Session = _sessionFactory.OpenSession();
        }
Exemplo n.º 11
0
        public DbContext(string connectionString, DbOption dbOption)
        {
            if (_sessionFactory == null)
            {
                _configuration = ConfigurationBuilder.New()
                    .ForSql2008(connectionString)
                    .MapEntities(GetEntityTypes());

                CreateOrUpdateDatabaseAndSchema(connectionString, dbOption);

                _sessionFactory = _configuration.BuildSessionFactory();
            }
            Session = _sessionFactory.OpenSession();
        }
Exemplo n.º 12
0
 private void CreateOrUpdateDatabaseAndSchema(string connectionString, DbOption dbOption)
 {
     var dbInit = new DatabaseInitializer(connectionString);
     if (dbOption == DbOption.DropAndRecreate || !dbInit.Exists())
     {
         dbInit.Drop();
         dbInit.Create();
         new SchemaExport(_configuration).Execute(true, true, false);
     }
     else
     {
         //attempt to update the schema
         new SchemaUpdate(_configuration).Execute(true, true);
     }
 }
Exemplo n.º 13
0
        //protected string configName;

        public BaseRepository(IOptionsSnapshot <DbOption> options, string dbConfig = DBConfig.MysqlCon)
        {
            if (_dbOption == null)
            {
                _dbOption = options.Get(dbConfig);
            }

            if (_dbConnection == null)
            {
                _dbConnection = ConnectionFactory.CreateConnection(_dbOption.DbType, _dbOption.ConnectionString);
                //if(_dbTransaction==null)
                //{
                //    _dbTransaction = _dbConnection.BeginTransaction();
                //}
            }
        }
Exemplo n.º 14
0
        private void CreateOrUpdateDatabaseAndSchema(string connectionString, DbOption dbOption)
        {
            var dbInit = new DatabaseInitializer(connectionString);

            if (dbOption == DbOption.DropAndRecreate || !dbInit.Exists())
            {
                dbInit.Drop();
                dbInit.Create();
                new SchemaExport(_configuration).Execute(true, true, false);
            }
            else
            {
                //attempt to update the schema
                new SchemaUpdate(_configuration).Execute(true, true);
            }
        }
        public DataContext CreateDbContext(string[] args)
        {
            DbOption selectedDbOption = AppConfigs.SelectedDbOption();

            var dbContextOptionsBuilder = new DbContextOptionsBuilder<DataContext>();
            switch (selectedDbOption.DbType)
            {
                case DbTypes.SqlServer:
                    dbContextOptionsBuilder.UseSqlServer(selectedDbOption.ConnectionStr);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            DbContextOptions<DataContext> dbContextOptions = dbContextOptionsBuilder.Options;
            return new DataContext(dbContextOptions);
        }
Exemplo n.º 16
0
        public static void DbCreateOrUpdate(DbOption option, Configuration cfg)
        {
            switch (option)
            {
            case DbOption.None:
                break;

            case DbOption.Update:
                new SchemaUpdate(cfg).Execute(false, true);
                break;

            case DbOption.Recreate:
                new SchemaExport(cfg).Execute(false, true, false);
                break;

            default:
                throw new ArgumentOutOfRangeException("option");
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// 获取连接数据库字符串
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        private string GetKernelConnectionStringWithDbName(string dbName)
        {
            string result  = "";
            var    kOption = new DbOption
            {
                DbType           = AppConfigurtaionServices.GetConfig(string.Format("DbOption:{0}:DbType", "Kernel")),
                ConnectionString = AppConfigurtaionServices.GetConfig(string.Format("DbOption:{0}:ConnectionString", "Kernel"))
            };

            if (!string.IsNullOrEmpty(kOption.ConnectionString))
            {
                var dbKernel = ConnectionFactory.CreateConnection(kOption.DbType, kOption.ConnectionString);
                DynamicParameters dyParameter = new DynamicParameters();
                dyParameter.Add("Name", dbName, DbType.String);
                var dbInfo = dbKernel.QueryFirst <Model.KernelDbInfoModel>("select * from v_DbInfo where Name=@Name", param: dyParameter);
                if (dbInfo == null)
                {
                    throw new Exception(string.Format("The database ({0}) connection configuration is not defined.", dbName));
                }
                result = string.Format(result, new object[] { dbInfo.ServerName, dbInfo.RealName, dbInfo.DbUserName, dbInfo.PassWord });
            }
            return(result);
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectFactory"/> class.
 /// </summary>
 /// <param name="provider">The provider.</param>
 /// <param name="dbOption">The db option.</param>
 public ConnectFactory(IDbProvider provider, DbOption dbOption)
 {
     this.provider = provider;
     this.dbOption = dbOption;
 }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MySqlDbProvider"/> class.
 /// </summary>
 /// <param name="dbOption">The db option.</param>
 public MySqlDbProvider(DbOption dbOption)
 {
     this.dbOption = dbOption;
 }
Exemplo n.º 20
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(ALLOWED_ORIGIN_POLICY,
                                  builder =>
                {
                    builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                });
            });

            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver               = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.DefaultValueHandling           = DefaultValueHandling.Include;
                options.SerializerSettings.StringEscapeHandling           = StringEscapeHandling.Default;
                options.SerializerSettings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
                options.SerializerSettings.DateTimeZoneHandling           = DateTimeZoneHandling.Utc;
                options.SerializerSettings.DateFormatHandling             = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.ConstructorHandling            = ConstructorHandling.AllowNonPublicDefaultConstructor;
            })
            .AddApplicationPart(typeof(HomeController).Assembly);

            #region Swagger

            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo()); });

            #endregion

            #region Db

            DbOption dbOption = AppConfigs.SelectedDbOption();

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                services.AddDbContext <DataContext>(builder => builder.UseSqlServer(dbOption.ConnectionStr));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            #endregion

            #region RabbitMQ

            RabbitMQConfigModel rabbitMqConfigModel = AppConfigs.GetRabbitMQConfigModel();
            RabbitMQOption      rabbitMqOption      = rabbitMqConfigModel.SelectedRabbitMQOption();

            services.AddSingleton(rabbitMqConfigModel);

            Type interfaceType       = typeof(ICapSubscribe);
            IEnumerable <Type> types = typeof(AccountCreated_VerificationMailSender)
                                       .Assembly
                                       .GetTypes()
                                       .Where(t => interfaceType.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract);
            foreach (Type t in types)
            {
                services.Add(new ServiceDescriptor(typeof(ICapSubscribe), t, ServiceLifetime.Transient));
            }

            services.AddCap(configurator =>
            {
                configurator.UseEntityFramework <DataContext>();
                configurator.UseRabbitMQ(options =>
                {
                    options.UserName    = rabbitMqOption.UserName;
                    options.Password    = rabbitMqOption.Password;
                    options.HostName    = rabbitMqOption.HostName;
                    options.VirtualHost = rabbitMqOption.VirtualHost;
                }
                                         );
            }
                            );

            #endregion

            #region IntegrationEventPublisher

            services.AddSingleton <ICapIntegrationEventPublisher, CapIntegrationEventPublisher>();

            #endregion

            #region HealthCheck

            IHealthChecksBuilder healthChecksBuilder = services.AddHealthChecks();

            healthChecksBuilder.AddUrlGroup(new Uri($"{AppConfigs.AppUrls().First()}/health-check"), HttpMethod.Get, name: "HealthCheck Endpoint");

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                healthChecksBuilder.AddSqlServer(dbOption.ConnectionStr, name: "Sql Server");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            switch (rabbitMqOption.BrokerType)
            {
            case MessageBrokerTypes.RabbitMq:
                string rabbitConnStr = $"amqp://{rabbitMqOption.UserName}:{rabbitMqOption.Password}@{rabbitMqOption.HostName}:5672{rabbitMqOption.VirtualHost}";
                healthChecksBuilder.AddRabbitMQ(rabbitConnStr, sslOption: null, name: "RabbitMq", HealthStatus.Unhealthy, new[] { "rabbitmq" });
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            services
            .AddHealthChecksUI(setup =>
            {
                setup.MaximumHistoryEntriesPerEndpoint(50);
                setup.AddHealthCheckEndpoint("StockManagement Project", $"{AppConfigs.AppUrls().First()}/healthz");
            })
            .AddInMemoryStorage();

            #endregion

            services.AddScoped <IAccountService, AccountService>();
        }
Exemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(ALLOWED_ORIGIN_POLICY,
                                  builder =>
                {
                    builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                });
            });

            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver               = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.DefaultValueHandling           = DefaultValueHandling.Include;
                options.SerializerSettings.StringEscapeHandling           = StringEscapeHandling.Default;
                options.SerializerSettings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
                options.SerializerSettings.DateTimeZoneHandling           = DateTimeZoneHandling.Utc;
                options.SerializerSettings.DateFormatHandling             = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.ConstructorHandling            = ConstructorHandling.AllowNonPublicDefaultConstructor;
            })
            .AddApplicationPart(typeof(HomeController).Assembly);


            #region Swagger

            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo()); });

            #endregion

            #region Db

            DbOption dbOption = AppConfigs.SelectedDbOption();

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                services.AddDbContext <DataContext>(builder => builder.UseSqlServer(dbOption.ConnectionStr));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            #endregion

            #region MassTransit

            MassTransitConfigModel massTransitConfigModel = AppConfigs.GetMassTransitConfigModel();
            MassTransitOption      massTransitOption      = massTransitConfigModel.SelectedMassTransitOption();

            services.AddSingleton(massTransitConfigModel);

            // A lot of log
            // services.AddSingleton<IConsumeObserver, BasicConsumeObserver>();
            // services.AddSingleton<ISendObserver, BasicSendObserver>();
            // services.AddSingleton<IPublishObserver, BasicPublishObserver>();

            services.AddMassTransitHostedService();
            services.AddMassTransit(x =>
            {
                x.AddConsumer <OrderStateOrchestrator>(
                    configurator => configurator
                    .UseFilter(new CustomTransactionFilter <OrderStateOrchestrator>())
                    )
                .Endpoint(configurator => { configurator.Name = $"{Program.STARTUP_PROJECT_NAME}.{nameof(OrderStateOrchestrator)}"; });

                switch (massTransitOption.BrokerType)
                {
                case MassTransitBrokerTypes.RabbitMq:
                    x.UsingRabbitMq((context, cfg) =>
                    {
                        cfg.Host(massTransitOption.HostName,
                                 massTransitOption.VirtualHost,
                                 hst =>
                        {
                            hst.Username(massTransitOption.UserName);
                            hst.Password(massTransitOption.Password);
                        });
                        cfg.UseConcurrencyLimit(massTransitConfigModel.ConcurrencyLimit);
                        cfg.UseRetry(retryConfigurator => retryConfigurator.SetRetryPolicy(filter => filter.Incremental(massTransitConfigModel.RetryLimitCount, TimeSpan.FromSeconds(massTransitConfigModel.InitialIntervalSeconds), TimeSpan.FromSeconds(massTransitConfigModel.IntervalIncrementSeconds))));
                        cfg.ConfigureEndpoints(context);
                    });
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            });

            #endregion

            #region IntegrationEventPublisher

            services.AddScoped <IIntegrationMessagePublisher, IntegrationMessagePublisher>();

            #endregion

            #region BusinessService

            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IPaymentServiceClient, PaymentServiceClient>();
            services.AddScoped <IShipmentServiceClient, ShipmentServiceClient>();

            services.AddScoped <IOrderStateMachineFactory, OrderStateMachineFactory>();

            #endregion

            #region DistributedLock

            DistributedLockOption distributedLockOption = AppConfigs.SelectedDistributedLockOption();
            services.AddSingleton(distributedLockOption);

            IDistributedLockManager distributedLockManager = distributedLockOption.DistributedLockType switch
            {
                DistributedLockTypes.SqlServer => new SqlServerDistributedLockManager(distributedLockOption.ConnectionStr),
                _ => throw new ArgumentOutOfRangeException()
            };

            services.AddSingleton(distributedLockManager);

            #endregion

            #region HealthCheck

            IHealthChecksBuilder healthChecksBuilder = services.AddHealthChecks();

            healthChecksBuilder.AddUrlGroup(new Uri($"{AppConfigs.AppUrls().First()}/health-check"), HttpMethod.Get, name: "HealthCheck Endpoint");

            healthChecksBuilder.AddSqlServer(distributedLockOption.ConnectionStr, name: "Sql Server - Distributed Lock");

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                healthChecksBuilder.AddSqlServer(dbOption.ConnectionStr, name: "Sql Server");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            switch (massTransitOption.BrokerType)
            {
            case MassTransitBrokerTypes.RabbitMq:
                string rabbitConnStr = $"amqp://{massTransitOption.UserName}:{massTransitOption.Password}@{massTransitOption.HostName}:5672{massTransitOption.VirtualHost}";
                healthChecksBuilder.AddRabbitMQ(rabbitConnStr, sslOption: null, name: "RabbitMq", HealthStatus.Unhealthy, new[] { "rabbitmq" });
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            services
            .AddHealthChecksUI(setup =>
            {
                setup.MaximumHistoryEntriesPerEndpoint(50);
                setup.AddHealthCheckEndpoint("OrderManagement Project", $"{AppConfigs.AppUrls().First()}/healthz");
            })
            .AddInMemoryStorage();

            #endregion
        }
Exemplo n.º 22
0
 public FileRepository(MasterDbContext masterDb, IOptionsMonitor <DbOption> option)
 {
     _option   = option.CurrentValue;
     _masterDb = masterDb;
 }
Exemplo n.º 23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WhereVisitor"/> class.
 /// </summary>
 /// <param name="dbPrivoder">The db privoder.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="funcVisits">The func visits.</param>
 public WhereVisitor(IDbProvider dbPrivoder, DbOption dbOption, IEnumerable <IFuncVisit> funcVisits) : base(dbPrivoder, dbOption, funcVisits)
 {
     _funcVisits = funcVisits;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MySqlSqlBuilder"/> class.
 /// </summary>
 /// <param name="dbProvider">The db provider.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="visitProvider">The visit provider.</param>
 /// <param name="typeMap"></param>
 public MySqlSqlBuilder(IDbProvider dbProvider, DbOption dbOption, IVisitProvider visitProvider, TypeMap typeMap) : base(visitProvider, dbProvider, dbOption, typeMap)
 {
 }
Exemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SelectVisitor"/> class.
 /// </summary>
 /// <param name="dbPrivoder">The db privoder.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="funcVisits">The func visits.</param>
 public SelectVisitor(IDbProvider dbPrivoder, DbOption dbOption, IEnumerable <IFuncVisit> funcVisits) : base(dbPrivoder, dbOption, funcVisits)
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HavingVisitor"/> class.
 /// </summary>
 /// <param name="dbProvider">The db provider.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="funcVisits">The func visits.</param>
 public HavingVisitor(IDbProvider dbProvider, DbOption dbOption, IEnumerable <IFuncVisit> funcVisits) : base(dbProvider, dbOption, funcVisits)
 {
 }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GroupVisitor"/> class.
 /// </summary>
 /// <param name="provider">The provider.</param>
 /// <param name="dbOption">The db option.</param>
 /// <param name="funcVisits">The func visits.</param>
 public GroupVisitor(IDbProvider provider, DbOption dbOption, IEnumerable <IFuncVisit> funcVisits) : base(provider, dbOption, funcVisits)
 {
     GroupDic = new Dictionary <string, string>();
 }
Exemplo n.º 28
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(ALLOWED_ORIGIN_POLICY,
                                  builder =>
                {
                    builder.AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                });
            });

            Assembly startupAssembly   = typeof(Startup).Assembly;
            Assembly apiAssembly       = typeof(HomeController).Assembly;
            Assembly consumersAssembly = typeof(StockCreatorConsumer).Assembly;
            Assembly businessAssembly  = typeof(IBusinessService).Assembly;
            Assembly dataAssembly      = typeof(DataContext).Assembly;
            Assembly exceptionAssembly = typeof(BaseException).Assembly;
            Assembly utilityAssembly   = typeof(IDistributedLockManager).Assembly;

            var allAssemblyList = new List <Assembly>
            {
                startupAssembly, apiAssembly, businessAssembly, dataAssembly, exceptionAssembly, utilityAssembly, consumersAssembly
            };

            services.AddControllers()
            .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver               = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.DefaultValueHandling           = DefaultValueHandling.Include;
                options.SerializerSettings.StringEscapeHandling           = StringEscapeHandling.Default;
                options.SerializerSettings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Full;
                options.SerializerSettings.DateTimeZoneHandling           = DateTimeZoneHandling.Utc;
                options.SerializerSettings.DateFormatHandling             = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.ConstructorHandling            = ConstructorHandling.AllowNonPublicDefaultConstructor;
            })
            .AddApplicationPart(typeof(HomeController).Assembly);

            services.AddHostedService <BusControlStarterHostedService>();

            #region Swagger

            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo()); });

            #endregion

            #region Db

            DbOption dbOption = AppConfigs.SelectedDbOption();

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                services.AddDbContext <DataContext>(builder => builder.UseSqlServer(dbOption.ConnectionStr));
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            #endregion

            #region MassTransit

            MassTransitConfigModel massTransitConfigModel = AppConfigs.GetMassTransitConfigModel();
            MassTransitOption      massTransitOption      = massTransitConfigModel.SelectedMassTransitOption();

            services.AddSingleton(massTransitConfigModel);

            services.AddSingleton <IConsumeObserver, BasicConsumeObserver>();
            services.AddSingleton <ISendObserver, BasicSendObserver>();
            services.AddSingleton <IPublishObserver, BasicPublishObserver>();

            services.AddMassTransit(configurator =>
            {
                configurator.AddConsumers(consumersAssembly);

                void ConfigureMassTransit(IBusFactoryConfigurator cfg)
                {
                    cfg.UseConcurrencyLimit(massTransitConfigModel.ConcurrencyLimit);
                    cfg.UseRetry(retryConfigurator => retryConfigurator.SetRetryPolicy(filter => filter.Incremental(massTransitConfigModel.RetryLimitCount, TimeSpan.FromSeconds(massTransitConfigModel.InitialIntervalSeconds), TimeSpan.FromSeconds(massTransitConfigModel.IntervalIncrementSeconds))));
                }

                void BindConsumer(IBusControl busControl, IServiceProvider provider)
                {
                    busControl.ConnectReceiveEndpoint($"{Program.STARTUP_PROJECT_NAME}.{nameof(StockCreatorConsumer)}",
                                                      endpointConfigurator => { endpointConfigurator.Consumer <StockCreatorConsumer>(provider); });

                    busControl.ConnectReceiveEndpoint($"{Program.STARTUP_PROJECT_NAME}.{nameof(AvailableStockSyncConsumer)}",
                                                      endpointConfigurator => { endpointConfigurator.Consumer <AvailableStockSyncConsumer>(provider); });
                }

                configurator.AddBus(provider =>
                {
                    IHost host             = null;
                    IBusControl busControl = massTransitOption.BrokerType switch
                    {
                        MassTransitBrokerTypes.RabbitMq
                        => Bus.Factory.CreateUsingRabbitMq(cfg =>
                        {
                            host = cfg.Host(massTransitOption.HostName,
                                            massTransitOption.VirtualHost,
                                            hst =>
                            {
                                hst.Username(massTransitOption.UserName);
                                hst.Password(massTransitOption.Password);
                            });
                            ConfigureMassTransit(cfg);
                        }),
                        _ => throw new ArgumentOutOfRangeException()
                    };

                    BindConsumer(busControl, provider.Container);

                    foreach (IConsumeObserver observer in provider.Container.GetServices <IConsumeObserver>())
                    {
                        host.ConnectConsumeObserver(observer);
                    }

                    foreach (ISendObserver observer in provider.Container.GetServices <ISendObserver>())
                    {
                        host.ConnectSendObserver(observer);
                    }

                    foreach (IPublishObserver observer in provider.Container.GetServices <IPublishObserver>())
                    {
                        host.ConnectPublishObserver(observer);
                    }

                    return(busControl);
                });
            });

            #endregion

            #region Mediatr

            services.AddMediatR(allAssemblyList.ToArray());
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(TransactionalBehavior <,>));

            #endregion

            #region DistributedLock

            DistributedLockOption distributedLockOption = AppConfigs.SelectedDistributedLockOption();
            services.AddSingleton(distributedLockOption);

            IDistributedLockManager distributedLockManager = distributedLockOption.DistributedLockType switch
            {
                DistributedLockTypes.SqlServer => new SqlServerDistributedLockManager(distributedLockOption.ConnectionStr),
                _ => throw new ArgumentOutOfRangeException()
            };

            services.AddSingleton(distributedLockManager);

            #endregion

            #region IntegrationEventPublisher

            services.AddScoped <IIntegrationEventPublisher, IntegrationEventPublisher>();

            #endregion

            #region HealthCheck

            IHealthChecksBuilder healthChecksBuilder = services.AddHealthChecks();

            healthChecksBuilder.AddUrlGroup(new Uri($"{AppConfigs.AppUrls().First()}/health-check"), HttpMethod.Get, name: "HealthCheck Endpoint");

            healthChecksBuilder.AddSqlServer(distributedLockOption.ConnectionStr, name: "Sql Server - Distributed Lock");

            switch (dbOption.DbType)
            {
            case DbTypes.SqlServer:
                healthChecksBuilder.AddSqlServer(dbOption.ConnectionStr, name: "Sql Server");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            switch (massTransitOption.BrokerType)
            {
            case MassTransitBrokerTypes.RabbitMq:
                string rabbitConnStr = $"amqp://{massTransitOption.UserName}:{massTransitOption.Password}@{massTransitOption.HostName}:5672{massTransitOption.VirtualHost}";
                healthChecksBuilder.AddRabbitMQ(rabbitConnStr, sslOption: null, name: "RabbitMq", HealthStatus.Unhealthy, new[] { "rabbitmq" });
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            services
            .AddHealthChecksUI(setup =>
            {
                setup.MaximumHistoryEntriesPerEndpoint(50);
                setup.AddHealthCheckEndpoint("StockManagement Project", $"{AppConfigs.AppUrls().First()}/healthz");
            })
            .AddInMemoryStorage();

            #endregion
        }