### Install EasyCaching.FasterKv Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/FasterKv.md Install the EasyCaching.FasterKv NuGet package using the .NET CLI. ```bash Install-Package EasyCaching.FasterKv ``` -------------------------------- ### Install Protobuf Serialization Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProtoBuf.md Install the EasyCaching.Serialization.Protobuf package using NuGet. ```powershell Install-Package EasyCaching.Serialization.Protobuf ``` -------------------------------- ### Install MessagePack Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/MessagePack.md Install the EasyCaching.Serialization.MessagePack NuGet package to enable MessagePack serialization. ```powershell Install-Package EasyCaching.Serialization.MessagePack ``` -------------------------------- ### Install EasyCaching.Disk Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Disk.md Install the EasyCaching.Disk NuGet package to enable disk caching functionality. ```powershell Install-Package EasyCaching.Disk ``` -------------------------------- ### Install EasyCaching.ResponseCaching NuGet Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ResponseCaching.md Use this command to install the necessary NuGet package for response caching. ```powershell Install-Package EasyCaching.ResponseCaching ``` -------------------------------- ### Install EasyCaching.InMemory Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/EasyCachingProvider.md Install the necessary NuGet package for using the in-memory caching provider. ```powershell Install-Package EasyCaching.InMemory ``` -------------------------------- ### Install EasyCaching.SQLite Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/SQLite.md Install the necessary NuGet package to enable SQLite caching functionality. ```powershell Install-Package EasyCaching.SQLite ``` -------------------------------- ### Install EasyCaching System.Text.Json Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/SystemTextJson.md Install the necessary NuGet package to enable System.Text.Json serialization with EasyCaching. ```powershell Install-Package EasyCaching.Serialization.SystemTextJson ``` -------------------------------- ### Install Memcached Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Memcached.md Install the EasyCaching.Memcached NuGet package to enable Memcached support. ```bash Install-Package EasyCaching.Memcached ``` -------------------------------- ### Basic Memcached Operations Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Memcached.md Demonstrates common operations like Set, Get, and Remove using the IEasyCachingProvider interface. Includes examples with and without data retrievers, and both synchronous and asynchronous calls. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly IEasyCachingProvider _provider; public ValuesController(IEasyCachingProvider provider) { this._provider = provider; } [HttpGet] public string Get() { //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Get var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); //Get without data retriever var res = _provider.Get("demo"); //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); } } ``` -------------------------------- ### appsettings.json Configuration Example Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/In-Memory.md Example JSON structure for configuring the in-memory cache settings in appsettings.json. ```json { "easycaching": { "inmemory": { "MaxRdSecond": 120, "EnableLogging": false, "LockMs": 5000, "SleepMs": 300, "DBConfig":{ "SizeLimit": 10000, "ExpirationScanFrequency": 60, "EnableReadDeepClone": true, "EnableWriteDeepClone": false } } } } ``` -------------------------------- ### Basic CRUD Operations with EasyCachingProvider Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/SQLite.md Demonstrates common caching operations like Remove, Set, and Get using the IEasyCachingProvider interface. Includes synchronous and asynchronous examples. ```csharp //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Get var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); //Get without data retriever var res = _provider.Get("demo"); //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); //RemoveByPrefix _provider.RemoveByPrefix("prefix"); //RemoveByPrefix async await _provider.RemoveByPrefixAsync("prefix"); ``` -------------------------------- ### Install EasyCaching.Redis NuGet Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/RedisCachingProvider.md Install the necessary NuGet package to enable Redis caching. ```powershell Install-Package EasyCaching.Redis ``` -------------------------------- ### Configure Hybrid Caching in Startup.cs Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/HybridCachingProvider.md Configure the hybrid caching provider in the ConfigureServices method of your Startup class. This example sets up an in-memory local cache and a Redis distributed cache, then combines them using the hybrid provider with a Redis bus for invalidation. ```csharp public void ConfigureServices(IServiceCollection services) { //other .. services.AddEasyCaching(options => { // local options.UseInMemory("m1"); // distributed options.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); config.DBConfig.Database = 5; }, "myredis"); // combine local and distributed options.UseHybrid(config => { config.TopicName = "test-topic"; config.EnableLogging = true; // specify the local cache provider name after v0.5.4 config.LocalCacheProviderName = "m1"; // specify the distributed cache provider name after v0.5.4 config.DistributedCacheProviderName = "myredis"; }, "h1") // use redis bus .WithRedisBus(busConf => { busConf.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); }); }); } ``` -------------------------------- ### Basic In-Memory Caching Operations Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/In-Memory.md Demonstrates common operations like Remove, Set, and Get with EasyCachingProvider in an ASP.NET Core Web API controller. Includes both synchronous and asynchronous examples. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly IEasyCachingProvider _provider; public ValuesController(IEasyCachingProvider provider) { this._provider = provider; } [HttpGet] public string Get() { //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Get var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); //Get without data retriever var res = _provider.Get("demo"); //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); } ``` -------------------------------- ### Install EasyCaching Packages Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProviderFactory.md Install the necessary EasyCaching packages for InMemory and Redis caching using the NuGet Package Manager. ```powershell Install-Package EasyCaching.InMemory Install-Package EasyCaching.Redis ``` -------------------------------- ### Install EasyCaching AspectCore and InMemory Packages Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/AspectCore.md Install the necessary NuGet packages for EasyCaching AspectCore integration and the InMemory caching provider. ```powershell Install-Package EasyCaching.Interceptor.AspectCore Install-Package EasyCaching.InMemory ``` -------------------------------- ### Install EasyCaching.LiteDB Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/LiteDB.md Install the LiteDB caching provider package using the NuGet Package Manager. ```powershell Install-Package EasyCaching.LiteDB ``` -------------------------------- ### Install EasyCaching Castle and InMemory Packages Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Castle.md Install the necessary NuGet packages for EasyCaching Castle interceptor and the InMemory caching provider. ```powershell Install-Package EasyCaching.Interceptor.Castle Install-Package EasyCaching.InMemory ``` -------------------------------- ### Basic Cache Operations (Async) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Disk.md Demonstrates asynchronous operations for removing, setting, and getting cache entries using the IEasyCachingProvider. Includes getting with and without a data retriever. ```csharp //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); //RemoveByPrefix async await _provider.RemoveByPrefixAsync("prefix"); ``` -------------------------------- ### Install EasyCaching NuGet Packages Source: https://github.com/dotnetcore/easycaching/blob/dev/README.md Install the desired EasyCaching provider package using the NuGet Package Manager Console. ```powershell Install-Package EasyCaching.InMemory Install-Package EasyCaching.Redis Install-Package EasyCaching.SQLite Install-Package EasyCaching.Memcached Install-Package EasyCaching.FasterKv ``` -------------------------------- ### Configure EasyCaching Services in Startup.cs Source: https://github.com/dotnetcore/easycaching/blob/dev/README.md Configure EasyCaching services in your .NET Core application's Startup class. This example shows configuration for InMemory and Redis caching providers. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { //configuration services.AddEasyCaching(options => { //use memory cache that named default options.UseInMemory("default"); // // use memory cache with your own configuration // options.UseInMemory(config => // { // config.DBConfig = new InMemoryCachingOptions // { // // scan time, default value is 60s // ExpirationScanFrequency = 60, // // total count of cache items, default value is 10000 // SizeLimit = 100 // }; // // the max random second will be added to cache's expiration, default value is 120 // config.MaxRdSecond = 120; // // whether enable logging, default is false // config.EnableLogging = false; // // mutex key's alive time(ms), default is 5000 // config.LockMs = 5000; // // when mutex key alive, it will sleep some time, default is 300 // config.SleepMs = 300; // }, "m2"); //use redis cache that named redis1 options.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); }, "redis1") .WithMessagePack() ; }); } } ``` -------------------------------- ### Install EasyCaching.CSRedis Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/CSRedis.md Install the EasyCaching.CSRedis NuGet package to add Redis caching capabilities to your project. ```powershell Install-Package EasyCaching.CSRedis ``` -------------------------------- ### Basic Cache Operations (Sync) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Disk.md Demonstrates synchronous operations for removing, setting, and getting cache entries using the IEasyCachingProvider. Includes getting with and without a data retriever. ```csharp //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Get var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); //Get without data retriever var res = _provider.Get("demo"); //RemoveByPrefix _provider.RemoveByPrefix("prefix"); ``` -------------------------------- ### Install EasyCaching Newtonsoft.Json Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/NewtonsoftJson.md Install the EasyCaching JSON serialization package using the NuGet Package Manager. ```powershell Install-Package EasyCaching.Serialization.Json ``` -------------------------------- ### Basic Caching Logic Without Interception Source: https://github.com/dotnetcore/easycaching/wiki/缓存拦截(AOP) This example demonstrates the manual implementation of caching logic, including checking the cache, fetching from the database if not found, and setting the cache. It highlights the repetitive nature of this pattern. ```cs public Product GetProduct(int id) { string cacheKey = $"product:{id}"; var val = _cache.Get(cacheKey); if(val != null) return val; val = _db.GetProduct(id); if(val != null) _cache.Set(cacheKey, val, expiration); return val; } ``` -------------------------------- ### Get Specific Redis Providers and Perform Operations Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/RedisCachingProvider.md Demonstrates how to get specific Redis providers by their names and perform basic string operations like StringSet and StringGet. ```csharp // GET api/values/redis3 [HttpGet] [Route("redis3")] public string GetRedis3() { var redis1 = factory.GetRedisProvider("redis1"); var redis2 = factory.GetRedisProvider("redis2"); _redis1.StringSet("keyredis1", "val"); var res1 = _redis1.StringGet("keyredis1"); var res2 = _redis2.StringGet("keyredis1"); return $"redis1 cached value: {res1}, redis2 cached value : {res2}"; } ``` -------------------------------- ### Install EasyCaching Hybrid Cache Packages Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/HybridCachingProvider.md Install the necessary NuGet packages for EasyCaching's hybrid caching functionality, including the core hybrid cache, in-memory cache, Redis cache, and Redis bus. ```powershell Install-Package EasyCaching.HybridCache Install-Package EasyCaching.InMemory Install-Package EasyCaching.Redis Install-Package EasyCaching.Bus.Redis ``` -------------------------------- ### appsettings.json Configuration for CSRedis Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/CSRedis.md Example JSON structure for configuring EasyCaching.CSRedis settings, including connection details, logging, and locking parameters. ```json "easycaching": { "csredis": { "MaxRdSecond": 120, "EnableLogging": false, "LockMs": 5000, "SleepMs": 300, "dbconfig": { "ConnectionStrings":[ "127.0.0.1:6388,defaultDatabase=13,poolsize=10" ], "Sentinels":[ "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" ], "ReadOnly": false } } } ``` -------------------------------- ### Install MemoryPack Serialization Package Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/MemoryPack.md Use this NuGet command to add the MemoryPack serialization package to your project. ```powershell Install-Package EasyCaching.Serialization.MemoryPack ``` -------------------------------- ### appsettings.json Configuration for Redis Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Redis.md Example JSON structure for configuring EasyCaching.Redis in appsettings.json. This includes settings for logging, locking, and database connection details. ```json "easycaching": { "redis": { "MaxRdSecond": 120, "EnableLogging": false, "LockMs": 5000, "SleepMs": 300, "dbconfig": { "Password": null, "IsSsl": false, "SslHost": null, "ConnectionTimeout": 5000, "AllowAdmin": true, "Endpoints": [ { "Host": "localhost", "Port": 6739 } ], "Database": 0 } } } ``` -------------------------------- ### Basic FasterKv Operations (Sync) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/FasterKv.md Demonstrates basic cache operations like Remove, Set, and Get using the IEasyCachingProvider interface in an ASP.NET Core Web API controller. Includes synchronous calls. ```csharp //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Get var res = _provider.Get("demo", () => "456", TimeSpan.FromMinutes(1)); //Get without data retriever var res = _provider.Get("demo"); ``` -------------------------------- ### Use EasyCachingProviderFactory in Controller Source: https://github.com/dotnetcore/easycaching/blob/dev/README.md Inject IEasyCachingProviderFactory into your controller to access caching providers by name. This example retrieves the 'redis1' provider. ```csharp public class ValuesController : Controller { // //when using single provider // private readonly IEasyCachingProvider _provider; //when using multiple provider private readonly IEasyCachingProviderFactory _factory; public ValuesController( //IEasyCachingProvider provider, IEasyCachingProviderFactory factory ) { //this._provider = provider; this._factory = factory; } [HttpGet] public string Handle() { //var provider = _provider; //get the provider from factory with its name var provider = _factory.GetCachingProvider("redis1"); //Set provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //Set Async await provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); } } ``` -------------------------------- ### Get Specific Redis Providers and Use Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProviderFactory.md Retrieve specific Redis providers by name using GetRedisProvider and perform operations like StringSet and StringGet. ```csharp // GET api/values/redis3 [HttpGet] [Route("redis3")] public string GetRedis3() { var redis1 = factory.GetRedisProvider("redis1"); var redis2 = factory.GetRedisProvider("redis2"); _redis1.StringSet("keyredis1", "val"); var res1 = _redis1.StringGet("keyredis1"); var res2 = _redis2.StringGet("keyredis1"); return $"redis1 cached value: {res1}, redis2 cached value : {res2}"; } } ``` -------------------------------- ### Asynchronous Cache Operations with EasyCachingProvider Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/LiteDB.md Demonstrates asynchronous cache operations including removing, setting, and getting cache entries. The 'GetAsync' method supports asynchronous data retrieval and expiration. ```csharp //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); //RemoveByPrefix async await _provider.RemoveByPrefixAsync("prefix"); ``` -------------------------------- ### Access Redis Caching Provider by Name Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/RedisCachingProvider.md Retrieve a configured Redis caching provider by its registered name using IEasyCachingProviderFactory. This example demonstrates fetching and using 'redis1'. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly IEasyCachingProviderFactory _factory; public ValuesController(IEasyCachingProviderFactory factory) { this._factory = factory; } // GET api/values/redis1 [HttpGet] [Route("redis1")] public string GetRedis1() { var provider = _factory.GetCachingProvider("redis1"); var val = $"redis1-{Guid.NewGuid()}"; var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); Console.WriteLine($"Type=redis1,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); return $"cached value : {res}"; } ``` -------------------------------- ### Named Serialization for Multiple Providers (0.6.0+) Source: https://github.com/dotnetcore/easycaching/wiki/缓存的序列化 Configures EasyCaching with named serializers for different Redis providers. The 'myredis' provider is explicitly set to use the serializer named 's1', which is MessagePack in this example. Multiple serializers can be added, but the provider uses the one matching its SerializerName. ```csharp services.AddEasyCaching(option => { var serializerName = "s1"; option.UseRedis(config => { config.DBConfig.Database = 7; config.DBConfig.Endpoints.Add(new ServerEndPoint("localhost", 6379)); config.SerializerName = serializerName; }, "myredis"); option.WithMessagePack("s1") .WithJson("myjson"); }); ``` -------------------------------- ### Configuring MessagePack with Custom Resolver for DateTime Accuracy Source: https://github.com/dotnetcore/easycaching/wiki/缓存的序列化 Configures EasyCaching to use MessagePack with a custom resolver to correctly handle DateTime serialization and avoid timezone issues. This example uses CSRedis and enables the custom resolver. ```csharp public void ConfigureServices(IServiceCollection services) { CompositeResolver.RegisterAndSetAsDefault( NativeDateTimeResolver.Instance, ContractlessStandardResolver.Instance ); services.AddControllers(); services.AddEasyCaching(option => { option.UseCSRedis(config => { config.DBConfig = new EasyCaching.CSRedis.CSRedisDBOptions { ConnectionStrings = new List { "127.0.0.1:6379,defaultDatabase=11,poolsize=10" } }; config.SerializerName = "mymsgpack"; }, "redis1"); option.WithMessagePack( x => { x.EnableCustomResolver = true; },"mymsgpack"); }); } ``` -------------------------------- ### Configure Disk Caching in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Disk.md Configure the EasyCaching service in your Startup class to use the disk cache provider. Specify the base path for the cache database. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Important step for SQLite Cache services.AddEasyCaching(option => { //use disk cache option.UseDisk(config => { config.DBConfig = new DiskDbOptions { BasePath = Path.GetTempPath() }; }); }); } } ``` -------------------------------- ### Configure SQLite Cache in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/SQLite.md Configure the EasyCaching service in your Startup class to use SQLite as the caching provider. Specify the database file name. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Important step for SQLite Cache services.AddEasyCaching(option => { //use sqlite cache option.UseSQLite(config => { config.DBConfig = new SQLiteDBOptions { FileName = "my.db" }; }); }); } } ``` -------------------------------- ### Configure Services for AspectCore in Startup (.NET Core 3.1+) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/AspectCore.md Configure services in the Startup class for .NET Core 3.1+, including EasyCaching, controllers, and AspectCore interceptor configuration. ```csharp public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddScoped(); services.AddEasyCaching(options => { options.UseInMemory("m1"); }); services.AddControllers(); services.AddTransient(); // AspectCore services.ConfigureAspectCoreInterceptor(options => options.CacheProviderName = "m1"); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } ``` -------------------------------- ### Configure FasterKv in Startup.cs Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/FasterKv.md Configure EasyCaching to use the FasterKv provider in your .NET Core application's Startup class. Ensure to set the SerializerName for FasterKv. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEasyCaching(option => { //use fasterkv cache option.UseFasterKv(config => { // fasterKv must be set SerializerName config.SerializerName = "msg"; }) .WithMessagePack("msg"); }); } } ``` -------------------------------- ### Configure Services and Container for .NET Core 3.1 Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Castle.md Configure services in the Startup class for .NET Core 3.1, including EasyCaching, controllers, and the Castle interceptor. Also, configure the Autofac container to enable the Castle interceptor. ```csharp public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddScoped(); services.AddEasyCaching(options => { options.UseInMemory("m1"); }); services.AddControllers(); services.AddTransient(); // for Castle services.ConfigureCastleInterceptor(options => options.CacheProviderName = "m1"); } // for castle public void ConfigureContainer(ContainerBuilder builder) { builder.ConfigureCastleInterceptor(); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } ``` -------------------------------- ### Configure EasyCaching Services Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/EasyCachingProvider.md Configure EasyCaching services in the Startup class, specifying in-memory caching providers with distinct names. ```csharp public void ConfigureServices(IServiceCollection services) { //other .. services.AddEasyCaching(option=> { //use memory cache option.UseInMemory("inmemory1"); //use memory cache option.UseInMemory("inmemory2"); }); } ``` -------------------------------- ### Configure Multiple Caching Providers in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProviderFactory.md Configure multiple InMemory and Redis caching providers with distinct names in the ConfigureServices method of your Startup class. ```csharp public void ConfigureServices(IServiceCollection services) { //other .. services.AddEasyCaching(option=> { //use memory cache option.UseInMemory("inmemory1"); //use memory cache option.UseInMemory("inmemory2"); //use redis cache option.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); }, "redis1"); //use redis cache option.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380)); }, "redis2"); }); } ``` -------------------------------- ### Configure EasyCaching with MemoryPack Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/MemoryPack.md Configure EasyCaching in your Startup class to use MemoryPack serialization. You can use the default name or specify a custom name. ```csharp public class Startup { //others... public void ConfigureServices(IServiceCollection services) { services.AddEasyCaching(options => { // with a default name [mempack] options.WithMemoryPack(); // with a custom name [myname] options.WithMemoryPack("myname"); // add some serialization settings options.WithMemoryPack(x => { x.StringEncoding = StringEncoding.Utf8; }, "cus"); }); } } ``` -------------------------------- ### Get and Use Redis Caching Provider Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProviderFactory.md Retrieve a Redis caching provider by its registered name using IEasyCachingProviderFactory and use it to cache a value. ```csharp // GET api/values/redis1 [HttpGet] [Route("redis1")] public string GetRedis1() { var provider = _factory.GetCachingProvider("redis1"); var val = $"redis1-{Guid.NewGuid()}"; var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); Console.WriteLine($"Type=redis1,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); return $"cached value : {res}"; } // GET api/values/redis2 [HttpGet] [Route("redis2")] public string GetRedis2() { var provider = _factory.GetCachingProvider("redis2"); var val = $"redis2-{Guid.NewGuid()}"; var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); Console.WriteLine($"Type=redis2,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); return $"cached value : {res}"; } ``` -------------------------------- ### Get and Use InMemory Caching Provider Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProviderFactory.md Retrieve an InMemory caching provider by its registered name using IEasyCachingProviderFactory and use it to cache a value. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly IEasyCachingProviderFactory _factory; public ValuesController(IEasyCachingProviderFactory factory) { this._factory = factory; } // GET api/values/inmem1 [HttpGet] [Route("inmem1")] public string GetInMemory() { var provider = _factory.GetCachingProvider("inmemory1"); var val = $"memory1-{Guid.NewGuid()}"; var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); Console.WriteLine($"Type=InMemory,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); return $"cached value : {res}"; } // GET api/values/inmem2 [HttpGet] [Route("inmem2")] public string GetInMemory() { var provider = _factory.GetCachingProvider("inmemory2"); var val = $"memory2-{Guid.NewGuid()}"; var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); Console.WriteLine($"Type=InMemory,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"); return $"cached value : {res}"; } } ``` -------------------------------- ### Configure Services for AspectCore in Startup (.NET Core 2.x) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/AspectCore.md Configure services in the Startup class for .NET Core 2.x, including EasyCaching, MVC, and AspectCore interceptor configuration. Note: .NET Core 2.x is no longer supported by EasyCaching versions above 0.8.0. ```csharp public class Startup { // others... public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddScoped(); services.AddEasyCaching(option=> { // use memory cache option.UseInMemory("default"); }); services.AddMvc(); return services.ConfigureAspectCoreInterceptor(options => { // Specify which provider you want to use options.CacheProviderName = "default"; }); } } ``` -------------------------------- ### Configure EasyCaching Response Caching in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ResponseCaching.md Add EasyCaching response caching services and configure the desired caching options in your application's Startup class. ```csharp public class Startup { //others... public void ConfigureServices(IServiceCollection services) { //add response caching services.AddEasyCachingResponseCaching(); //which type of caching that you want to use services.AddEasyCaching(option=> { // option.Usexxx(...); }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //use response caching app.UseEasyCachingResponseCaching(); } } ``` -------------------------------- ### Access HybridCachingProvider in an API Controller Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/HybridCachingProvider.md Inject IHybridProviderFactory into your API controller to retrieve an instance of IHybridCachingProvider. This allows you to perform caching operations like getting and setting cache entries. ```csharp [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHybridCachingProvider _hybrid; public ValuesController(IHybridProviderFactory hybridFactory) { this._hybrid = hybridFactory.GetHybridCachingProvider("h1"); } // GET api/values [HttpGet] public ActionResult> Get() { var res = _hybrid.Get("cacheKey"); return new string[] { "value1", "value2", res.Value }; } // GET api/values/set [HttpGet("set")] public ActionResult Set() { // the same key for different value of _hybrid.Set("cacheKey", "val-from app1", TimeSpan.FromMinutes(1)); return "ok"; } } ``` -------------------------------- ### Applying EasyCachingAble Attribute for Query Interception Source: https://github.com/dotnetcore/easycaching/wiki/缓存拦截(AOP) Use the EasyCachingAble attribute on an interface method to automatically intercept query operations. This example sets an absolute expiration time of 10 seconds for the cache. ```cs public interface IDemoService { [EasyCachingAble(Expiration = 10)] string GetCurrentUtcTime(); } ``` -------------------------------- ### Configure EasyCaching with System.Text.Json Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/SystemTextJson.md Configure EasyCaching services in your application's Startup class to use System.Text.Json for serialization. This includes options for default naming, custom naming, and custom serialization settings. ```csharp public class Startup { //others... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEasyCaching(options => { // with a default name [json] options.WithSystemTextJson(); // with a custom name [myname] options.WithSystemTextJson("myname"); // add some serialization settings Action easycaching = x => { }; options.WithSystemTextJson(easycaching, "easycaching_setting"); }); } } ``` -------------------------------- ### Configure Protobuf Serialization Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/ProtoBuf.md Configure EasyCaching to use Protobuf serialization with a default or custom name. ```csharp public class Startup { //others... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEasyCaching(options => { // with a default name [proto] options.WithProtobuf(); // with a custom name [myname] options.WithProtobuf("myname"); }); } } ``` -------------------------------- ### Implement Service Interface Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Castle.md Provide an implementation for the service interface, containing the actual business logic that will be intercepted by EasyCaching. ```csharp public class DemoService : IDemoService { public void DeleteSomething(int id) { System.Console.WriteLine("Handle delete something.."); } public string GetCurrentUtcTime() { return System.DateTime.UtcNow.ToString(); } public string PutSomething(string str) { return str; } } ``` -------------------------------- ### Configure Services for .NET Core 2.x with Castle Interceptor Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Castle.md Configure services in the Startup class for .NET Core 2.x, including EasyCaching and the Castle interceptor. This method returns an IServiceProvider and configures the interceptor with a specified cache provider name. ```csharp public class Startup { //others... public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddScoped(); services.AddEasyCaching(option => { // use memory cache option.UseInMemory("default"); }); services.AddMvc(); return services.ConfigureCastleInterceptor(options => { // Specify which provider you want to use options.CacheProviderName = "default"; }); } } ``` -------------------------------- ### Configure Memcached Service Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Memcached.md Configure the Memcached caching provider in the Startup class by adding servers to the connection configuration. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Important step for Memcached Cache services.AddEasyCaching(option => { //use memmemcachedory cache option.UseMemcached(config => { config.DBConfig.AddServer("127.0.0.1", 11211); }); }); } } ``` -------------------------------- ### Configure Redis Caching in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/RedisCachingProvider.md Configure EasyCaching to use Redis as a caching provider in your application's startup class. Multiple Redis endpoints can be configured. ```csharp public void ConfigureServices(IServiceCollection services) { //other .. services.AddEasyCaching(option=> { //use redis cache option.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); }, "redis1"); //use redis cache option.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380)); }, "redis2"); }); } ``` -------------------------------- ### Configure Redis Caching via appsettings.json Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Redis.md Configure the Redis caching provider by referencing a name in your Startup class, with the actual configuration stored in appsettings.json. This approach centralizes configuration. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { //other services. //Important step for Redis Caching services.AddEasyCaching(option => { option.UseRedis(Configuration, "myredisname"); }); } } ``` -------------------------------- ### Basic FasterKv Operations (Async) Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/FasterKv.md Demonstrates asynchronous cache operations like RemoveAsync, SetAsync, and GetAsync using the IEasyCachingProvider interface in an ASP.NET Core Web API controller. Includes asynchronous calls. ```csharp //Remove Async await _provider.RemoveAsync("demo"); //Set Async await _provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1)); //Get Async var res = await _provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1)); //Get without data retriever Async var res = await _provider.GetAsync("demo"); ``` -------------------------------- ### Configure LiteDB Cache in Startup Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/LiteDB.md Configure the LiteDB caching provider in your application's Startup class by adding it to the EasyCaching options. Specify the database file name for LiteDB. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //Important step for SQLite Cache services.AddEasyCaching(option => { //use litedb cache option.UseLiteDB(config => { config.DBConfig = new LiteDBDBOptions { FileName = "s1.ldb" }; }); }); } } ``` -------------------------------- ### Configure In-Memory Cache via C# Code Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/In-Memory.md Configure the in-memory caching provider using C# code in your Startup class. Supports simple and custom configurations. ```csharp services.AddEasyCaching(options => { // use memory cache with a simple way options.UseInMemory("default"); // use memory cache with your own configuration options.UseInMemory(config => { config.DBConfig = new InMemoryCachingOptions { // scan time, default value is 60s ExpirationScanFrequency = 60, // total count of cache items, default value is 10000 SizeLimit = 100, // below two settings are added in v0.8.0 // enable deep clone when reading object from cache or not, default value is true. EnableReadDeepClone = true, // enable deep clone when writing object to cache or not, default value is false. EnableWriteDeepClone = false, }; // the max random second will be added to cache's expiration, default value is 120 config.MaxRdSecond = 120; // whether enable logging, default is false config.EnableLogging = false; // mutex key's alive time(ms), default is 5000 config.LockMs = 5000; // when mutex key alive, it will sleep some time, default is 300 config.SleepMs = 300; }, "default1"); }); ``` -------------------------------- ### Basic Cache Retrieval Logic Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/InterceptorOverview.md This method demonstrates a common pattern for retrieving data from a cache, falling back to a database if the data is not found. It includes logic to set the data in the cache if it was retrieved from the database. ```csharp public Product GetProduct(int id) { string cacheKey = $"product:{id}"; var val = _cache.Get(cacheKey); if(val != null) return val; val = _db.GetProduct(id); if(val != null) _cache.Set(cacheKey, val, expiration); return val; } ``` -------------------------------- ### Configure Default MessagePack Serialization Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/MessagePack.md Configure EasyCaching to use MessagePack serialization with a default name. This is the simplest way to enable it. ```csharp services.AddEasyCaching(options => { // with a default name [mskpack] options.WithMessagePack(); // with a custom name [myname] options.WithMessagePack("myname"); // add some serialization settings options.WithMessagePack(x => { // If this setting is true, you should custom the resolver by yourself // If this setting is false, also the default behavior, it will use ContractlessStandardResolver only x.EnableCustomResolver = true; }, "cus"); }); ``` -------------------------------- ### Configure In-Memory Cache via appsettings.json Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/In-Memory.md Configure the in-memory caching provider by referencing settings in your appsettings.json file. Ensure the configuration path matches. ```csharp services.AddEasyCaching(options => { //use memory cache options.UseInMemory(Configuration, "default", "easycaching:inmemory"); }); ``` -------------------------------- ### Configure Host for AspectCore in .NET Core 3.1+ Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/AspectCore.md Configure the HostBuilder in Program.cs to use AspectCore's service context for .NET Core 3.1 and later versions. ```csharp // for aspcectcore using AspectCore.Extensions.Hosting; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) // for aspcectcore .UseServiceContext() ; ``` -------------------------------- ### Configure Program for .NET Core 3.1 with Autofac Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Castle.md Configure the Program class for .NET Core 3.1 to use Autofac as the service provider factory, which is required for Castle interceptor integration. ```csharp // for castle using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) // for castle .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ; ``` -------------------------------- ### Default Redis Configuration with BinaryFormatter Source: https://github.com/dotnetcore/easycaching/wiki/缓存的序列化 Configures EasyCaching to use Redis with the default BinaryFormatter for serialization. Ensure your types are marked with [Serializable] if using this default. ```csharp services.AddEasyCaching(option => { option.UseRedis(config => { config.DBConfig.Database = 7; config.DBConfig.Endpoints.Add(new ServerEndPoint("localhost", 6379)); }); }); ``` -------------------------------- ### Basic Caching Operations with IEasyCachingProvider Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/CSRedis.md Demonstrates fundamental caching operations like removing, setting, and retrieving cache entries using the IEasyCachingProvider interface in an ASP.NET Core Web API controller. ```csharp [Route("api/[controller]")] public class ValuesController : Controller { private readonly IEasyCachingProvider _provider; public ValuesController(IEasyCachingProvider provider) { this._provider = provider; } [HttpGet] public string Get() { //Remove _provider.Remove("demo"); //Set _provider.Set("demo", "123", TimeSpan.FromMinutes(1)); //others ... } } ``` -------------------------------- ### Configure Redis Caching via C# Code Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/Redis.md Configure the Redis caching provider directly in your Startup class using C# code. Ensure to specify the server endpoints. ```csharp public class Startup { //... public void ConfigureServices(IServiceCollection services) { //other services. //Important step for Redis Caching services.AddEasyCaching(option => { option.UseRedis(config => { config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); }, "redis1"); }); } } ``` -------------------------------- ### Configuring MessagePack Serialization (Pre-0.6.0) Source: https://github.com/dotnetcore/easycaching/wiki/缓存的序列化 Adds the MessagePack serialization package and configures EasyCaching to use MessagePack for Redis. Note that in versions prior to 0.6.0, only one serializer could be specified. ```bash dotnet add package EasyCaching.Serialization.MessagePack ``` ```csharp services.AddEasyCaching(option => { option.UseRedis(config => { config.DBConfig.Database = 7; config.DBConfig.Endpoints.Add(new ServerEndPoint("localhost", 6379)); }) .WithMessagePack() ; ``` -------------------------------- ### Custom Options Extension Interface Source: https://github.com/dotnetcore/easycaching/wiki/缓存的序列化 Defines the IEasyCachingOptionsExtension interface, which must be implemented to configure custom services for EasyCaching. ```csharp public interface IEasyCachingOptionsExtension { void AddServices(IServiceCollection services); } ``` -------------------------------- ### Configure EasyCaching with Default JSON Serialization Source: https://github.com/dotnetcore/easycaching/blob/dev/docs/NewtonsoftJson.md Configure EasyCaching services in your application to use the default JSON serializer. This is typically done in the ConfigureServices method of your Startup class. ```csharp services.AddEasyCaching(options => { // with a default name [json] options.WithJson(); // with a custom name [myname] options.WithJson("myname"); // add some serialization settings Action easycaching = x => { x.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; }; options.WithJson(easycaching, "easycaching_setting"); // add some serialization settings // after version 0.8.1, full control of JsonSerializerSettings Action jsonNET = x => { x.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; x.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); }; options.WithJson(jsonNET, "json.net_setting"); }); ```