Memory Cache in dotnet core

前端 未结 3 1346
心在旅途
心在旅途 2021-02-13 14:05

I am trying to write a class to handle Memory cache in a .net core class library. If I use not the core then I could write

using System.Runtime.Caching;
using S         


        
3条回答
  •  不知归路
    2021-02-13 14:52

    If you using Asp.net core you no need to custom SingleTon for cache, because Asp.net core is supported DI for your Cache class.

    To using IMemoryCache to set data to the memory of the server you can do as below:

    public void Add(T o, string key)
    {
        if (IsEnableCache)
        {
            T cacheEntry;
    
            // Look for cache key.
            if (!_cache.TryGetValue(key, out cacheEntry))
            {
                // Key not in cache, so get data.
                cacheEntry = o;
    
                // Set cache options.
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    // Keep in cache for this time, reset time if accessed.
                    .SetSlidingExpiration(TimeSpan.FromSeconds(7200));
    
                // Save data in cache.
                _cache.Set(key, cacheEntry, cacheEntryOptions);
            }
        }
    }
    

    For more detail, you can read the article implement in-memory in asp.net core

提交回复
热议问题