示例#1
0
        private static void MostSimpleCacheManager()
        {
            var config = new ConfigurationBuilder()
                .WithSystemRuntimeCacheHandle()
                .Build();

            var cache = new BaseCacheManager<string>(config);
            // or
            var cache2 = CacheFactory.FromConfiguration<string>(config);
        }
示例#2
0
        public ISeadQueryCache Create()
        {
            var config = new CacheManager.Core.ConfigurationBuilder()
                         //.WithSystemRuntimeCacheHandle()
                         .WithDictionaryHandle()
                         .Build();
            var cache = new CacheManager.Core.BaseCacheManager <object>(config);

            return(new SeadQueryCache(cache));
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(options =>
            {
                options.AllowEmptyInputInBodyModelBinding = true;
            }).AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
            });

            // hosted service that runs every 7 days to fetch and update cache
            services.AddHostedService <DataUpdateWorker>();

            // needed to load configuration from appsettings.json
            services.AddOptions();

            // register the data provider
            services.AddTransient <IDataProvider, DataProviderImpl>();

            // register my custom http client
            services.AddHttpClient <ICustomHttpClient, CustomHttpClient>()
            .ConfigurePrimaryHttpMessageHandler(handler =>
                                                new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            });

            // in memory caching service added. NB: distributed cache such as redis will be used in production
            services.AddMemoryCache();

            //load general configuration from appsettings.json
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            // inject counter and rules stores
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            // the clientId/clientIp resolvers use it.
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // configuration (resolvers, counter key builders)
            services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>();

            var config = new CacheManager.Core.ConfigurationBuilder()
                         .WithMicrosoftMemoryCacheHandle("PlayersCache", new MemoryCacheOptions())
                         .Build();

            services.AddSingleton <IPlayersCacheRepository>(serviceProvider => new PlayersCacheRepository(new BaseCacheManager <PlayerModel>(config), serviceProvider.GetRequiredService <ILogger <PlayersCacheRepository> >()));

            CommonCachingService.RawDataCache = new BaseCacheManager <DataResponseModel>(config);
        }
示例#4
0
        private static void EditExistingConfiguration()
        {
            var config = new ConfigurationBuilder()
                .WithSystemRuntimeCacheHandle()
                    .EnableStatistics()
                .Build();

            config = new ConfigurationBuilder(config)
                .WithMicrosoftLogging(f => f.AddConsole())
                .Build();
        }
示例#5
0
        private static void MostSimpleCacheManagerWithLogging()
        {
var config = new ConfigurationBuilder()
    .WithMicrosoftLogging(l => l.AddConsole(LogLevel.Information))
    .WithSystemRuntimeCacheHandle()
    .Build();

var cache = new BaseCacheManager<string>(config);
            // or
            var cache2 = CacheFactory.FromConfiguration<string>(config);
        }
示例#6
0
        /// <summary>
        /// 负责调用autofac框架实现业务逻辑层和数据仓储层程序集中的类型对象的创建
        /// 负责创建MVC控制器类的对象(调用控制器中的有参构造函数),接管DefaultControllerFactory的工作
        /// </summary>
        public static void Register()
        {
            var cacheConfig = ConfigurationBuilder.BuildConfiguration(settings => settings.WithMaxRetries(1000).WithMemcachedCacheHandle("cacheManager/memcached"));
            var builder     = new ContainerBuilder();

            //缓存注册
            builder.RegisterGeneric(typeof(BaseCacheManager <>))
            .WithParameters(new[]
            {
                new TypedParameter(typeof(ICacheManagerConfiguration), cacheConfig)
            })
            .As(typeof(ICacheManager <>))
            .SingleInstance();
            //builder.RegisterAssemblyTypes(this.ThisAssembly)
            //.Where(t => t.IsAssignableTo<IService>())
            //.AsImplementedInterfaces()
            //.InstancePerLifetimeScope();
            ExceptionlessClient.Default.Configuration.UseInMemoryStorage();
            ExceptionlessClient.Default.Configuration.UseReferenceIds();
            ExceptionlessClient.Default.Configuration.SetDefaultMinLogLevel(MinLogLevel());
            // 日志
            builder.RegisterType <ExceptionLessLogger>().As <ILogger>().SingleInstance();
            builder.RegisterType <AuthService>().As <IAuthService>().SingleInstance();
            // 获取包含继承了IService接口类的程序集
            builder.RegisterModule <KStar.Form.Mvc.WebServiceModule>();
            builder.RegisterModule <KStar.Domain.WebServiceModule>();
            builder.RegisterModule <KStar.Form.Domain.WebServiceModule>();
            builder.RegisterModule <KStar.Platform.WebServiceModule>();


            // Register your MVC controllers. (MvcApplication is the name of
            // the class in Global.asax.)
            builder.RegisterControllers(Assembly.GetExecutingAssembly())
            .PropertiesAutowired()    // Enable property injection
            .InstancePerLifetimeScope();

            // OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinderProvider();

            // OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule <AutofacWebTypesModule>();

            // OPTIONAL: Enable property injection in view pages.
            //builder.RegisterSource(new ViewRegistrationSource());

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            // Set the dependency resolver to be Autofac.
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
示例#7
0
        private void AddCache(IServiceCollection services)
        {
            var cacheManagerConfig =
                ConfigurationBuilder.BuildConfiguration(cfg =>
            {
                cfg.WithGzJsonSerializer()
                .WithMicrosoftMemoryCacheHandle("runTimeMemory");
            });

            services.AddSingleton(cacheManagerConfig);
            services.AddCacheManager();
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            var cacheConfig  = new CacheManager.Core.ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build();
            var cache        = new BaseCacheManager <object>(cacheConfig);
            var cacheAdapter = new CacheManagerAdapter(cache);
            var keyStrategy  = new HttpStandardKeyStrategy(cacheAdapter);
            var handler      = new HttpCachingHandler(cacheAdapter, keyStrategy);
            var api          = new MyAPI(handler);

            api.BaseUri = new Uri("http://localhost:3670");
            services.AddSingleton <IMyAPI>(api);
        }
示例#9
0
        private void AddCache(IServiceCollection services)
        {
            var cacheManagerConfig =
                ConfigurationBuilder.BuildConfiguration(cfg =>
            {
                cfg.WithGzJsonSerializer()
                .WithMicrosoftMemoryCacheHandle("runTimeMemory");
            });

            services.AddSingleton(cacheManagerConfig);
            services.AddCacheManager();

            services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo("DataProtection-Keys"));
        }
示例#10
0
        private void AddCache(IServiceCollection services)
        {
            var cacheManagerConfig =
                ConfigurationBuilder.BuildConfiguration(cfg =>
            {
                cfg.WithJsonSerializer()
                .WithRedisConfiguration("redis", Configuration.GetConnectionString("Redis"))
                .WithRedisBackplane("redis")
                .WithRedisCacheHandle("redis", true);
            });

            services.AddSingleton(cacheManagerConfig);
            services.AddCacheManager();

            var redisConnection = ConnectionMultiplexer.Connect(Configuration.GetConnectionString("Redis"));

            services.AddSingleton <IConnectionMultiplexer>(redisConnection);

            services.AddDataProtection()
            .PersistKeysToRedis(redisConnection, "DataProtection-Keys");
        }
示例#11
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options => options
                                                         .UseSqlServer(_configuration.GetConnectionString("Chest")));

            services
            .AddControllers()
            .AddNewtonsoftJson(
                options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            services.AddSingleton <IHttpStatusCodeMapper, HttpStatusCodeMapper>();
            services.AddSingleton <ILogLevelMapper, DefaultLogLevelMapper>();

            if (!TimeSpan.TryParse(_configuration.GetValue <string>("CacheExpiration"), out var cacheExpiration))
            {
                cacheExpiration = TimeSpan.FromMinutes(5);
            }

            var cacheManagerConfiguration = new CacheManager.Core.ConfigurationBuilder()
                                            .WithJsonSerializer()
                                            .WithMicrosoftMemoryCacheHandle()
                                            .WithExpiration(ExpirationMode.Sliding, cacheExpiration)
                                            .Build();

            services.AddEFSecondLevelCache();
            services.AddSingleton(typeof(ICacheManager <>), typeof(BaseCacheManager <>));
            services.AddSingleton(typeof(ICacheManagerConfiguration), cacheManagerConfiguration);

            // Configure versions
            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(2, 0);
            });

            var clientSettings = _configuration.GetSection("ChestClientSettings").Get <ClientSettings>();

            services.AddApiKeyAuth(clientSettings);

            // Configure swagger
            services.AddSwaggerGen(options =>
            {
                // Specifying versions
                options.SwaggerDoc("v2", CreateInfoForApiVersion("v2", false));

                // This call remove version from parameter, without it we will have version as parameter for all endpoints in swagger UI
                options.OperationFilter <RemoveVersionFromParameter>();

                // This make replacement of v{version:apiVersion} to real version of corresponding swagger doc, i.e. v1
                options.DocumentFilter <ReplaceVersionWithExactValueInPath>();

                // This exclude endpoint not specified in swagger version, i.e. MapToApiVersion("99")
                options.DocInclusionPredicate((version, desc) =>
                {
                    if (!desc.TryGetMethodInfo(out var methodInfo))
                    {
                        return(false);
                    }

                    var versions = methodInfo.DeclaringType
                                   .GetCustomAttributes(true)
                                   .OfType <ApiVersionAttribute>()
                                   .SelectMany(attr => attr.Versions);

                    var maps = methodInfo.DeclaringType
                               .GetCustomAttributes(true)
                               .OfType <MapToApiVersionAttribute>()
                               .SelectMany(attr => attr.Versions)
                               .ToArray();

                    return(versions.Any(v => $"v{v.ToString()}" == version) && (maps.Length == 0 || maps.Any(v => $"v{v.ToString()}" == version)));
                });

                if (!string.IsNullOrWhiteSpace(clientSettings?.ApiKey))
                {
                    options.AddApiKeyAwareness();
                }
            }).AddSwaggerGenNewtonsoftSupport();

            // Default settings for NewtonSoft Serializer
            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    },
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting        = Formatting.None
                };

                settings.Converters.Add(new StringEnumConverter());

                return(settings);
            };

            services.AddAutoMapper(typeof(AutoMapperProfile));

            services.AddScoped <IDataService, DataService>();
            services.AddScoped <ILocalizedValuesRepository, LocalizedValuesRepository>();
            services.AddScoped <ILocalizedValuesService, LocalizedValuesService>();
            services.AddScoped <ILocalesRepository, LocalesRepository>();
            services.AddScoped <ILocalesService, LocalesService>();

            services.AddScoped <IAuditRepository, AuditRepository>();
            services.AddScoped <IAuditService, AuditService>();
        }
示例#12
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options => options
                                                         .UseSqlServer(this.configuration.GetConnectionString("Chest")));

            services
            .AddMvcCore()
            .AddApiExplorer()
            .AddDataAnnotations()
            .AddJsonFormatters()
            .AddJsonOptions(
                options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

            var cacheManagerConfiguration = new CacheManager.Core.ConfigurationBuilder()
                                            .WithJsonSerializer()
                                            .WithMicrosoftMemoryCacheHandle()
                                            .Build();

            services.AddEFSecondLevelCache();
            services.AddSingleton(typeof(ICacheManager <>), typeof(BaseCacheManager <>));
            services.AddSingleton(typeof(ICacheManagerConfiguration), cacheManagerConfiguration);

            services.AddSwaggerGen(options =>
            {
                options.DefaultLykkeConfiguration("v1", "Chest API");
                options.SchemaFilter <NullableTypeSchemaFilter>();
            });

            // Default settings for NewtonSoft Serializer
            JsonConvert.DefaultSettings = () =>
            {
                var settings = new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver {
                        NamingStrategy = new SnakeCaseNamingStrategy()
                    },
                    NullValueHandling = NullValueHandling.Ignore,
                };

                settings.Converters.Add(new StringEnumConverter());

                return(settings);
            };

            services.AddScoped <IDataService, DataService>();

            services.AddCors(options =>
            {
                /*//options.AddPolicy("spa", policy =>
                 * //{
                 * //    policy.WithOrigins("http://localhost:5008")
                 * //        .AllowAnyHeader()
                 * //        .AllowAnyMethod();
                 * //});*/
            });
        }