Skip to content

thiagoloureiro/EasyMemoryCache

Repository files navigation

EasyMemoryCache

Build status

NuGet

.NET Component to easily implement MemoryCache (sync and async) for your .NET Core Application

How to Use:

Open Package Manager Console and run:

Install-Package EasyMemoryCache

Usage:

First, register the component in your Application:

.AddEasyCache(new CacheSettings() { ... })

.NET Core Console Example

//setup our DI
var serviceProvider = new ServiceCollection()
    .AddEasyCache(new CacheSettings() { ... })
    .BuildServiceProvider();

var caching = serviceProvider.GetService<ICaching>();
return caching;

ASP.NET Core Example (Startup.cs)

services.AddEasyCache(Configuration.GetSection("CacheSettings").Get<CacheSettings>());

Configuration example: (Redis)

"CacheSettings": {
    "CacheProvider": "Redis",
    "IsDistributed": true,
    "RedisConnectionString": "localhost:6379,password=xxx=,ssl=False,abortConnect=False"
  }

For MemoryCache

 "IsDistributed": false,
 "CacheProvider": "MemoryCache",

InMemory cache will be used instead of Redis

Then inject the interface where do you want to use, for example:

private readonly ICaching _caching;
private string UserKeyCache => "UserKey";

public UserService(ICaching caching)
{
     _caching = caching;
}

Async:

var lstStringFromAsync = await _caching.GetOrSetObjectFromCacheAsync(CacheKeyNameForAsync, 20, ReturnListOfStringAsync);

With parameters:

var lstStringFromAsync = await _caching.GetOrSetObjectFromCacheAsync(CacheKeyNameForAsync, 20, () => ReturnListOfStringAsync(param));

Sync:

var lstString = _caching.GetOrSetObjectFromCache(CacheKeyName, 20, ReturnListOfString);

Check the code sample in the src directory