1

I am new to DotNet Core. I have created a WEB API using .NEt Core. I have a requirement to implement cache manager in this API. I have a set of record which will get updated once in a day, so i wanted this data stored in an object in memory and call database only if a change has been detected(or at a definite interval, say 3 hrs). I already tried implementing a logic in my app. but wanted to see if we have a specific packages already available !

Please help me.

Thanks in advance.

1
  • did u considered using http cache instead of caching in memory ? In my opinion it's a better solution than caching object in memory Commented Feb 25, 2017 at 11:41

2 Answers 2

12

Asp.Net has built-in cache libraries that you can use. They are available in .Net core as well, e.g. you can read about therm here. It's a bit too long to describe here, but generally you need to register it in you services:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
    }
}

Then you can inject IMemoryCache in your services. It requires NuGet package Microsoft.Extensions.Caching.Memory.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I will read about this and will implement
3

You can use ASP.NET cache which is available in Microsoft.Extensions.Caching.Memory Nuget Package. Install this package if it is not available.

Then you need to register the cache memory service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
}

Consume your cache service into a controller:

public class CacheController : Controller
{
    private readonly IMemoryCache _cache;
    public TokenController(IMemoryCache cache) 
    {
        _config = config;
     }
}

Use the below function to get or set cache data:

public T GetOrSet<T>(string cacheKey, Func<T> getItemCallBack)
{
    var item = _cache.Get<T>(cacheKey);
    if (item == null)
    {
        item = getItemCallBack();
        _cache.Set(cacheKey, item, CacheKeysWithOption.CacheOption);
    }
    return item;
}

And consume GetOrSet:

public IActionResult CacheTryGetValueSet()
{
    var list = GetOrSet(CacheKeysWithOption.Entry, GetStringList);
    return new JsonResult(list);
}

[NonAction]
public List<String> GetStringList()
{
    List<String> str = new List<string>()
    {
        "aaaaa",
        "sssdasdas",
        "dasdasdas"
    };
    return str;
}

1 Comment

CacheKeysWithOption.Entry is just string key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.