예제 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <StoreContextSeed>();

            services.AddAutoMapper(this.GetType().Assembly);

            services.AddControllers();

            services.AddServicesToApi();
            services.AddIdentityServices(Configuration);

            services.AddCors(option =>
                             option.AddPolicy(CorsPolicyName, policy => {
                policy.AllowAnyHeader().AllowAnyMethod().WithOrigins(Configuration["FrontEndClient"]);
            })
                             );

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

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


            services.AddSingleton <IConnectionMultiplexer>(c => {
                var configuration = ConfigurationOptions
                                    .Parse(Configuration.GetConnectionString("Redis"), true);

                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API", Version = "v1"
                });
            });
        }
예제 #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <CoffeeShopContext>(x =>
                                                      x.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
            services.AddSingleton <ConnectionMultiplexer>(c => {
                var config = ConfigurationOptions.Parse(_configuration.GetConnectionString("Redis"),
                                                        true);
                return(ConnectionMultiplexer.Connect(config));
            });
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errors = actionContext.ModelState
                                 .Where(e => e.Value.Errors.Count > 0)
                                 .SelectMany(x => x.Value.Errors)
                                 .Select(x => x.ErrorMessage).ToArray();

                    var errorResponce = new ValidationErrorResponce
                    {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponce));
                };
            });

            services.AddSwaggerDocumentation();

            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
        }
예제 #3
0
파일: Startup.cs 프로젝트: feifles/OvoNovo
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-US");
                options.SupportedCultures     = new List <CultureInfo> {
                    new CultureInfo("en-US"), new CultureInfo("en-US")
                };
            });

            services.AddAutoMapper(typeof(MappingProfiles));

            services.AddControllers();

            services.AddDbContext <StoreContext>(x => x.UseSqlite(_config.GetConnectionString("ConnectionStrWindows")));
            services.AddDbContext <AppIdentityDbContext>(x => x.UseSqlServer(_config.GetConnectionString("IdentityConnection")));


            //Adding Redis to enable 'Cart' funcionality
            services.AddSingleton <IConnectionMultiplexer>(c =>
            {
                var configuration = ConfigurationOptions.Parse(_config.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();
            services.AddIdentityServices(_config);

            services.AddSwaggerDocumentation();
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                });
            });
        }
예제 #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Basket.Api", Version = "v1"
                });
            });

            services.AddSingleton <ConnectionMultiplexer>(x =>
            {
                var config = ConfigurationOptions.Parse(Configuration.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(config));
            });

            services.AddTransient <IBasketRepository, BasketRepository>();
            services.AddTransient <IBasketContext, BasketContext>();
            services.AddTransient <EventBusRabbitMQProducer>();
            services.AddSingleton <IRabbitMqConnection>(x =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration["EventBus:HostName"],
                    UserName = Configuration["EventBus:UserName"],
                    Password = Configuration["EventBus:Password"]
                };
                return(new RabbitMqConnection(factory));
            });
            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MappingProfile());
            });
            IMapper mapper = mapperConfig.CreateMapper();

            services.AddSingleton(mapper);
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );

            services.AddDbContext <Honors20Context>(options =>
                                                    options.UseMySql(
                                                        Configuration.GetConnectionString("Default")));



            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IUsersRepository, UserRepository>();
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <IBasketRepository, BasketRepository>();
            services.AddScoped <IBasketProductRepository, BasketProductRepository>();
            services.AddScoped <IBasketService, BasketService>();
            services.AddScoped <IOrderProductsRepository, OrderProductRepository>();
            services.AddScoped <IOrdersRepository, OrdersRepository>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IReviewRepository, ReviewRepository>();
            services.AddScoped <IReviewService, ReviewService>();

            var redisConfigurationOptions = ConfigurationOptions.Parse("localhost:6379");

            services.AddStackExchangeRedisCache(redisCacheConfig =>
            {
                redisCacheConfig.ConfigurationOptions = redisConfigurationOptions;
            });

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(1000);
            });
        }
예제 #6
0
        // 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 => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //扩展httpcontext
            //services.AddHttpContextAccessor();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 获取配置项
            //services.AddDbContext<IAltasDbContext,MySqlDbContext>(opts =>
            //{
            //    opts.
            //})

            #endregion

            #region hangfire配置
            string redisConn = this.Configuration.GetSection("redisConn:redisConnStr").Value;
            string redisPwd  = this.Configuration.GetSection("redisConn:redisPwd").Value;
            var    hgOpts    = ConfigurationOptions.Parse(redisConn);
            hgOpts.AllowAdmin = true;
            hgOpts.Password   = redisPwd;
            //var _redisContext = ConnectionMultiplexer.Connect(hgOpts);
            //services.AddHangfire(x => x.UseRedisStorage(_redisContext, new RedisStorageOptions()
            //{
            //    Prefix = "{altas_web_hangfire}:"
            //}));
            #endregion
        }
예제 #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #region 获取配置项

            SugarDbConn.DbConnectStr = this.Configuration.GetSection("DbConn:mysqlConn").Value;
            GlobalParamsDto.RpcUname = this.Configuration.GetSection("RpcUser:Username").Value;
            GlobalParamsDto.RpcPwd   = this.Configuration.GetSection("RpcUser:Password").Value;

            #endregion

            #region hangfire配置

            string redisConn = this.Configuration.GetSection("redisConn:redisConnStr").Value;
            string redisPwd  = this.Configuration.GetSection("redisConn:redisPwd").Value;
            var    hgOpts    = ConfigurationOptions.Parse(redisConn);
            hgOpts.AllowAdmin = true;
            hgOpts.Password   = redisPwd;

            #endregion

            //services.AddTransient<ISysAreaService, SysAreaService>();
            //services.AddTransient<ISysDicService, SysDicService>();
            //services.AddTransient<ISysFuncService, SysFuncService>();
            //services.AddTransient<ISysMenuService, SysMenuService>();
            //services.AddTransient<ISysRoleService, SysRoleService>();
            //services.AddTransient<ISysUserService, SysUserService>();
        }
예제 #8
0
        public static IConnectionMultiplexer ConcretConnection(string conString = "")
        {
            IConnectionMultiplexer con = null;

            ConfigurationOptions opt = null;

            if (!string.IsNullOrEmpty(conString))
            {
                opt = ConfigurationOptions.Parse(conString);
            }
            else
            {
                opt = new ConfigurationOptions()
                {
                    AllowAdmin      = true,
                    KeepAlive       = 180,
                    DefaultDatabase = 0,
                    ConnectRetry    = 3,
                    ConnectTimeout  = 3000,
                    EndPoints       =
                    {
                        { "localhost", 7000 },
                        { "localhost", 7001 },
                        { "localhost", 7002 },
                        { "localhost", 7003 },
                        { "localhost", 7004 },
                        { "localhost", 7005 },
                    },
                    DefaultVersion = new Version("3.2.0")
                }
            };

            con = ConnectionMultiplexer.Connect(opt);

            return(con);
        }
    }
예제 #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IEventBus>(s => new RabbitMQEventBus(
                                                  Configuration.GetValue <string>("EventBus:Rabbit"),
                                                  "checkout1"
                                                  ));

            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var connectionString = Configuration.GetConnectionString("Basket");
                var configuration    = ConfigurationOptions.Parse(connectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });
            services.AddSingleton <ICatalogService>(sp => new CatalogAPIClient(
                                                        Configuration.GetValue <string>("Services:Catalog.API"),
                                                        new HttpClient()
                                                        ));
            services.AddTransient <IBasketRepository, RedisBasketRepository>();
            services.AddControllers();
            services.AddSwaggerGen(
                c => {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "BasketAPI",
                    Version = "v1"
                });
                c.IncludeXmlComments(Path.Combine(
                                         AppContext.BaseDirectory,
                                         $"{ Assembly.GetExecutingAssembly().GetName().Name }.xml"
                                         ));
            }

                );
        }
예제 #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // Di container
        public void ConfigureServices(IServiceCollection services)
        {
            // Registering automapper as service.
            services.AddAutoMapper(typeof(MappingProfiles)); // mapping profiles is class where we have provided mappings.
            services.AddControllers();

            // add dbcontext as service
            // ordering dosent matter here. ordering matter in middleware section
            // since we are using sqllite for development purpose so we are using sqllite.
            services.AddDbContext <StoreContext>(x =>
                                                 x.UseSqlite(_config.GetConnectionString("DefaultConnection")));

            // add identiy db context as service
            services.AddDbContext <AppIdentityDbContext>(x =>
                                                         x.UseSqlite(_config.GetConnectionString("IdentityConnection")));

            // Adding redis connnection settiong
            services.AddSingleton <ConnectionMultiplexer>(c => {
                var configuration = ConfigurationOptions.Parse(
                    _config.GetConnectionString("Redis"), true);
                configuration.Password = _config.GetConnectionString("RedisPassword");

                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();     // coming from extension method.
            services.AddIdentityServices(_config); // coming from extension
            services.AddSwaggerDocumentation();    // coming from swagger extension


            // adding CORS
            services.AddCors(opt => {
                opt.AddPolicy("CorsPolicy", policy => {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                });
            });
        }
예제 #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddCors(o => o.AddPolicy(_policyName, builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            // Adding EF Core
            var connectionString = Configuration[Constants.DataStore.SqlConnectionString];

            services.AddDbContext <CollegeSqlDbContext>(o => o.UseSqlServer(connectionString));

            // Application Services
            services.AddScoped <IProfessorsSqlBll, ProfessorsSqlBll>();
            services.AddScoped <IProfessorsSqlDal, ProfessorsSqlDal>();

//#if DEBUG
//            // services.AddScoped<IProfessorsSqlDal, MockPaymentGateway>();
//#else
//            // services.AddScoped<IProfessorsSqlDal, RealPaymentGateway>();
//#endif

            // Redis Cache Dependencies
            services.AddSingleton(sp =>
            {
                var configuration = ConfigurationOptions.Parse(Configuration[Constants.DataStore.RedisConnectionString], true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            // Redis Cache Related
            services.AddScoped <IRedisCacheDbContext, RedisCacheDbContext>();
            services.AddScoped <IRedisCacheDbDal, RedisCacheDbDal>();
        }
예제 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <ConnectionMultiplexer>(sp => {
                var configuration = ConfigurationOptions.Parse(Configuration.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddTransient <IBasketContext, BasketContext>();
            services.AddTransient <IBasketRepository, BasketRepository>();
            services.AddAutoMapper(typeof(Startup));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "Basket API", Version = "v1"
                });
            });

            services.AddControllers();
            services.AddSingleton <IRabbitMQConnection>(sp =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration["EventBus:HostName"]
                };
                if (!string.IsNullOrEmpty(Configuration["EventBus:UserName"]))
                {
                    factory.UserName = Configuration["EventBus:UserName"];
                }
                if (!string.IsNullOrEmpty(Configuration["EventBus:Password"]))
                {
                    factory.Password = Configuration["EventBus:Password"];
                }
                return(new RabbitMQConnection(factory));
            });
            services.AddSingleton <EventBusRabbitMQProducer>();
        }
예제 #13
0
        static void Main()
        {
            // Configuration options and patterns
            string redisConfiguration = "localhost:6379";                               // Store *basic* information in a string
            var    options            = ConfigurationOptions.Parse(redisConfiguration); // create a ConfigurationOptions instance

            options.AllowAdmin   = true;                                                // and set specific details with options
            options.Ssl          = false;
            options.ConnectRetry = 1;
            options.HighPrioritySocketThreads = true;

            // Multiplexer is intended to be reused
            ConnectionMultiplexer redisMultiplexer = ConnectionMultiplexer.Connect(options);

            // The database reference is a lightweight passthrough object intended to be used and discarded
            IDatabase db = redisMultiplexer.GetDatabase();

            // All Redis commands and data types are supported and available through the API

            StringExercises.Exercises(db);

            HashExercises.Exercises(db);

            ListExercises.Exercises(db);

            SetExercises.Exercises(db);

            SortedSetExercises.Exercises(db);

            GeoLocationExercises.Exercises(db);

            HllExercises.Exercises(db);

            StreamExercises.Exercises(db);

            PubSubExercises.Exercises(redisMultiplexer);
        }
        private async Task ConnectAsync(CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            if (_redis != null)
            {
                return;
            }

            await _connectionLock.WaitAsync(token);

            try
            {
                if (_redis == null)
                {
                    if (_options.ConfigurationOptions != null)
                    {
                        _redisConfig = _options.ConfigurationOptions;
                    }
                    else
                    {
                        _redisConfig = ConfigurationOptions.Parse(_options.Configuration);
                    }
                    _redisConfig.AllowAdmin = true;
                    _redisConfig.SetDefaultPorts();
                    _connection = await ConnectionMultiplexer.ConnectAsync(_redisConfig);

                    RegistenConnectionEvent(_connection);
                    _redis  = _connection.GetDatabase();
                    _server = _connection.GetServer(_redisConfig.EndPoints[0]);
                }
            }
            finally
            {
                _connectionLock.Release();
            }
        }
예제 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddControllers();
            services.AddDbContext <StoreContext>(x =>
            {
                x.UseSqlite(_config.GetConnectionString("DefaultConnection"));
            });

            //Identity - Passo 5: Adicionando contexto do Identity como serviço adicional e criando chave "IdentityConnection" em "appSettingsDevelopment.json"
            //Após este passo executar migration
            services.AddDbContext <AppIdentityDbContext>(x => {
                x.UseSqlite(_config.GetConnectionString("IdentityConnection"));
            });

            //Configura Redis
            services.AddSingleton <IConnectionMultiplexer>(c =>
            {
                var configuration = ConfigurationOptions.Parse(_config.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();
            //Identity - Passo 8: configurando serviços do identity
            services.AddIdentityServices(_config);
            services.AddSwaggerDocumentation();
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .WithOrigins("https://localhost:4200", "http://localhost");
                });
            });
        }
예제 #16
0
        private ConfigurationOptions GetRedisConfiguration()
        {
            ConfigurationOptions configOptions;

            if (!string.IsNullOrEmpty(options.ConnectionString))
            {
                configOptions = ConfigurationOptions.Parse(options.ConnectionString);
                if (options.DatabaseNo == null)
                {
                    configOptions.DefaultDatabase = 2;
                }
            }
            else
            {
                configOptions = new ConfigurationOptions
                {
                    ConnectRetry    = options.ConnectRetry ?? 4,
                    DefaultDatabase = options.DatabaseNo ?? 2,
                    SyncTimeout     = options.SyncTimeout ?? 10000,
                    EndPoints       =
                    {
                        { options.Hostname, 6380 }
                    },
                    Password = options.Password
                };
            }

            if (options.IsLocalDocker)
            {
                IPAddress address  = GetIPAddress(configOptions.EndPoints[0]);
                EndPoint  endpoint = configOptions.EndPoints[0];
                configOptions.EndPoints.Remove(endpoint);
                configOptions.EndPoints.Add(new IPEndPoint(address, 6379));
            }

            return(configOptions);
        }
        public static IServiceCollection AddCaching(this IServiceCollection services, RedisConnection redisConnection, TimeSpan timeout)
        {
            var configurationOptions      = ConfigurationOptions.Parse(redisConnection.ToString());
            var cacheManagerConfiguration = new ConfigurationBuilder()
                                            .WithJsonSerializer(new JsonSerializerSettings()
            {
                NullValueHandling     = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, new JsonSerializerSettings()
            {
                NullValueHandling     = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            })
                                            //.WithUpdateMode(CacheUpdateMode.Up)
                                            .WithRedisConfiguration("Redis", ConnectionMultiplexer.Connect(configurationOptions))
                                            .WithRedisCacheHandle("Redis")
                                            .WithExpiration(ExpirationMode.None, timeout)
                                            .Build();

            services.AddTransient(typeof(ICacheManagerConfiguration), x => cacheManagerConfiguration);
            services.AddSingleton(typeof(ICacheManager <>), typeof(BaseCacheManager <>));

            return(services);
        }
예제 #18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <IBasketRepository, BasketRepository>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddDbContext <StoreContext>(x =>

                                                 x.UseSqlite(_configuration.GetConnectionString("DefaultConnection")));

            services.AddSingleton <IConnectionMultiplexer>(c => {
                var config = ConfigurationOptions.Parse(_configuration
                                                        .GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(config));
            });

            services.AddCors(opt => {
                opt.AddPolicy("CorsPolicy", policy => {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                });
            });
        }
        public void IntTest()
        {
            var config = ConfigurationOptions.Parse("localhost");

            var bf = FilterRedisBuilder.Build <int>(config, "NormalTest", 10000, 0.01);

            var len   = 10;
            var array = new int[len];

            for (int i = 0; i < len; i++)
            {
                array[i] = i;
            }

            Assert.All(bf.Add(array), r => Assert.True(r));
            Assert.All(bf.Contains(array), r => Assert.True(r));

            Assert.True(bf.All(array));

            bf.Clear();

            Assert.All(bf.Contains(array), r => Assert.False(r));
            Assert.False(bf.All(array));
        }
예제 #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddControllers();
            // product dbContext
            services.AddDbContext <StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
            // identity dbContext
            services.AddDbContext <AppIdentityDbContext>(x =>
            {
                x.UseSqlite(_config.GetConnectionString("IdentityConnection"));
            });



            services.AddSingleton <IConnectionMultiplexer>(c =>
            {
                var configuration = ConfigurationOptions.Parse(_config.GetConnectionString("Redis"),
                                                               true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();
            services.AddIdentityServices(_config);
            services.AddSwaggerDocumentation();

            // add cors support  allow angular use the service
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
        /// <summary>
        /// Конструктор помощника для глобального хранилища.
        /// </summary>
        /// <param name="helper">Помощник для локального хранилища.</param>
        /// <param name="configSettings">Конфигурационные настройки.</param>
        public CoreCachingStorageGlobalHelper(
            CoreCachingStorageLocalHelper helper,
            ICoreCachingConfigSettings configSettings,
            CoreCachingResourceErrors coreCachingResourceErrors
            )
        {
            Helper = helper;

            DbIndex = configSettings.DbIndex;

            ChannelPatternForRemoveData    = Helper.CacheKeyPrefix + ".remove.*";
            ChannelPatternForRemoveAllData = Helper.CacheKeyPrefix + ".flush*";

            var options = string.IsNullOrWhiteSpace(configSettings.Hosts)
                ?
                          ConfigurationOptions.Parse(string.Concat(configSettings.Host, ":", configSettings.Port))
                :
                          ConfigurationOptions.Parse(configSettings.Hosts);

            options.AllowAdmin         = true;
            options.Password           = configSettings.Password;
            options.AbortOnConnectFail = false;
            options.ConnectTimeout     = configSettings.ConnectTimeout;

            Connection = ConnectionMultiplexer.Connect(options);

            if (!Connection.IsConnected)
            {
                throw new CoreBaseException(
                          string.Format(
                              coreCachingResourceErrors.GetStringFormatUnableToConnectToRedis(),
                              configSettings.CoreBaseExtJsonSerialize(CoreBaseExtJson.OptionsForLogger)
                              )
                          );
            }
        }
예제 #22
0
파일: Startup.cs 프로젝트: steven715/skinet
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddControllers();


            services.AddSingleton <IConnectionMultiplexer>(c =>
            {
                var configuration = ConfigurationOptions.Parse(_config
                                                               .GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();
            services.AddIdentityService(_config);
            services.AddSwaggerDocumentation();
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                });
            });
        }
예제 #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson(options =>
                                                        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                        );

            services.AddScoped <ITokenService, TokenService>();
            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddControllers();
            services.AddDbContext <StoreContext>
                (x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));

            services.AddDbContext <AppIdentityDbContext>(x =>
            {
                x.UseSqlite(_config.GetConnectionString("IdentityConnection"));
            });



            services.AddSingleton <IConnectionMultiplexer>(c => {
                var configuration = ConfigurationOptions.Parse(_config.GetConnectionString("Redis"),
                                                               true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddApplicationServices();
            services.AddIdentityServices(_config);
            services.AddSwaggerDocumentation();
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200/").AllowAnyOrigin();
                });
            });
        }
        /// <summary>
        /// Sets up data protection to persist session keys in Redis.
        /// </summary>
        /// <param name="builder">The <see cref="IDataProtectionBuilder"/> used to set up data protection options.</param>
        /// <param name="redisConnectionString">The connection string specifying the Redis instance and database for key storage.</param>
        /// <returns>
        /// The <paramref name="builder" /> for continued configuration.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="builder" /> or <paramref name="redisConnectionString" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrown if <paramref name="redisConnectionString" /> is empty.
        /// </exception>
        public static IDataProtectionBuilder PersistKeysToRedis(this IDataProtectionBuilder builder, string redisConnectionString)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (redisConnectionString == null)
            {
                throw new ArgumentNullException(nameof(redisConnectionString));
            }

            if (redisConnectionString.Length == 0)
            {
                throw new ArgumentException("Redis connection string may not be empty.", nameof(redisConnectionString));
            }

            var configuration = ConfigurationOptions.Parse(redisConnectionString, true);

            configuration.ResolveDns = true;

            return(builder.Use(ServiceDescriptor.Singleton <IXmlRepository>(services =>
                                                                            new RedisXmlRepository(configuration, services.GetRequiredService <ILogger <RedisXmlRepository> >()))));
        }
예제 #25
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <KestrelServerOptions>(options => {
                var ports = GetDefinedPorts(Configuration);
                options.Listen(IPAddress.Any, ports.httpPort, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
                });

                options.Listen(IPAddress.Any, ports.grpcPort, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http2;
                });
            });

            services.AddGrpc(options =>
            {
                options.EnableDetailedErrors = true;
            });

            services.Configure <SessionSettings>(Configuration);

            services.AddSingleton <ConnectionMultiplexer>(sp =>
            {
                var settings      = sp.GetRequiredService <IOptions <SessionSettings> >().Value;
                var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);

                configuration.ResolveDns = true;

                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddTransient <ISessionRepository, RedisSessionRepository>();
            services.AddControllers();
            services.AddOptions();
        }
예제 #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <ConnectionMultiplexer>(s =>
            {
                var _configaretion = ConfigurationOptions.Parse(Configuration.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(_configaretion));
            });

            services.AddTransient <ICartContext, CartContext>();
            services.AddTransient <ICartRepository, CartRepository>();

            services.AddControllers();

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

            services.AddAutoMapper(typeof(Startup));

            services.AddSingleton <IRabbitMQConnection>(s =>
            {
                var factory = new ConnectionFactory()
                {
                    HostName = Configuration["EventBus:HostName"]
                };

                factory.UserName = Configuration["EventBus:UserName"];
                factory.UserName = Configuration["EventBus:Password"];

                return(new RabbitMQConnection(factory));
            });
            services.AddSingleton <EventBusRabbitMQProducer>();
        }
        /// <summary>
        /// Sessionを設定する。
        /// </summary>
        /// <param name="services"></param>
        public static void Session(this IServiceCollection services, IConfiguration Configuration)
        {
            //Sessionの設定
            var sessionConnectionString = Configuration.GetConnectionString("AppCache");

            //Console.WriteLine($"調査用_Redis接続文字列【{sessionConnectionString}】");

            if (string.IsNullOrEmpty(sessionConnectionString))
            {
                Console.WriteLine("Sessionの格納にメモリキャッシュを利用");
                //Radisなどへの接続文字列が指定されていない場合(APIサーバなどセッションを使わない場合)は、仮でメモリを使用する。
                services.AddDistributedMemoryCache();
            }
            else
            {
                Console.WriteLine("Sessionの格納にRedisキャッシュを利用");
                //セッション情報はRedisに格納するよう修正
                services.AddStackExchangeRedisCache(redisCacheConfig =>
                {
                    redisCacheConfig.ConfigurationOptions = ConfigurationOptions.Parse(sessionConnectionString);
                });
            }

            services.AddSession(o =>
            {
                //コンテキストパスがある場合はCookie名に付与する。(同じブラウザでみた場合にクッキー値を上書きしないように。)
                var contextPathInfo = Configuration.GetContextPathInfo();

                o.Cookie.Name = $".MM.Session.{contextPathInfo.NoSlashContextPath}";
                o.IdleTimeout = AuthTimeoutSpan; //セッションの有効期間
                //o.Cookie.HttpOnly = true;
                //o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                o.Cookie.SameSite    = SameSiteMode.None;
                o.Cookie.IsEssential = true;
            });
        }
예제 #28
0
        /// <summary>
        /// 自定义一些注入规则
        /// </summary>
        /// <param name="container"></param>
        private static AppSettings InitCustomIoc(ContainerBuilder container)
        {
            //appsettings
            var appsettingsJson          = File.ReadAllText("appsettings.json");
            var appSettings              = JsonConvert.DeserializeObject <AppSettings>(appsettingsJson);
            var appConfigurtaionServices = new AppConfigurtaionServices(null)
            {
                AppSettings = appSettings
            };

            container.RegisterInstance(appConfigurtaionServices).As <IAppConfigurtaionServices>();
            //RedisConfig
            var configuration = ConfigurationOptions.Parse(appSettings.RedisConfig.ServerList, true);

            configuration.ResolveDns = true;
            var redis = ConnectionMultiplexer.Connect(configuration);

            container.RegisterInstance(redis).As <ConnectionMultiplexer>();
            container.RegisterType <RedisProvider>().As <ICacheProvider>();
            //IHttpClient
            container.RegisterType <HttpContextAccessor>().As <IHttpContextAccessor>().SingleInstance();
            container.RegisterType <StandardHttpClient>().As <IHttpClient>().SingleInstance();
            return(appSettings);
        }
예제 #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <StoreContext>(x => x.UseNpgsql(_configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <UserContext>(x => x.UseNpgsql(_configuration.GetConnectionString("UserConnection")));

            services.AddSingleton <IConnectionMultiplexer>(c => {
                var configuration = ConfigurationOptions.Parse(_configuration.GetConnectionString("Redis"), true);
                return(ConnectionMultiplexer.Connect(configuration));
            });

            services.AddAutoMapper(typeof(MappingProfiles));
            services.AddApplicationServices();
            services.AddUserServices(_configuration);
            services.AddSwaggerDocumentation();
            services.AddCors(option =>
            {
                option.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3200");
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://krooter.store");
                });
            });
        }
        public async Task IntTestAsync()
        {
            var config = ConfigurationOptions.Parse("localhost");

            var bf = FilterRedisBuilder.Build(config, "IntTestAsync", 10000, 0.01);

            var len   = 10;
            var array = new int[len];

            for (int i = 0; i < len; i++)
            {
                array[i] = i;
            }

            Assert.All(await bf.AddAsync(array), r => Assert.True(r));
            Assert.All(await bf.ContainsAsync(array), r => Assert.True(r));

            Assert.True(await bf.AllAsync(array));

            await bf.ClearAsync();

            Assert.All(await bf.ContainsAsync(array), r => Assert.False(r));
            Assert.False(await bf.AllAsync(array));
        }