InMemoryCaching

We found 10 examples in language CSharp for this search. You will see 36 fragments of code.

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddMemoryCache();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "InMemoryCaching", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "InMemoryCaching v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        
        public bool Set(CacheEntry entry, bool addOnly = false)
        {
            if (addOnly)
            {
                if (!_memory.TryAdd(entry.Key, entry))
                {
                    if (!_memory.TryGetValue(entry.Key, out _) || entry.ExpiresAt >= DateTimeOffset.UtcNow)
                        return false;

                    _memory.AddOrUpdate(entry.Key, entry, (k, cacheEntry) => entry);
                }
            }
            else
            {
                _memory.AddOrUpdate(entry.Key, entry, (k, cacheEntry) => entry);
            }

            return true;
        }

        public CacheValue<T> Get<T>(string key)
        {
            if (!_memory.TryGetValue(key, out var cacheEntry))
            {
                return CacheValue<T>.NoValue;
            }

            try
            {
                var value = cacheEntry.GetValue<T>(true);
                return new CacheValue<T>(value, true);
            }
            catch (Exception)
            {
                return CacheValue<T>.NoValue;
            }
        }

        public void Remove(string key)
        {
            _memory.TryRemove(key, out _);
        }

        public List<string> Keys(string prefix)
        {
            return _memory.Keys.Where(x => x.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
        }

        public bool Exists(string cacheKey)
        {
            return _memory.TryGetValue(cacheKey, out _);
        }


        public bool Add<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (Exists(key))
                return false;
            Set(key, value, expiresIn);
            return true;
        }

        public T Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (_cache.TryGetValue(key, out T _value))
                return _value;

            return default(T);
        }

        public bool Set<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (expiresIn.HasValue)
                _cache.Set(key, value, new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(expiresIn.Value.TotalSeconds)
                });
            else
                _cache.Set(key, value);

            return true;
        }

        public bool Exists(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            return _cache.TryGetValue(key, out _);
        }


        public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
        {
            var map = new Dictionary<string, T>();

            foreach (string key in keys)
                map[key] = Get<T>(key);

            return map;
        }

        public int SetAll<T>(IDictionary<string, T> values, TimeSpan? expiresIn = null)
        {
            if (values == null || values.Count == 0)
                return 0;

            var list = new List<bool>();

            foreach (var entry in values)
                list.Add(Set(entry.Key, entry.Value, expiresIn));

            return list.Count(r => r);
        }


        public bool Add<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (Exists(key))
                return false;
            Set(key, value, expiresIn);
            return true;
        }

        public T Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (_cache.TryGetValue(key, out T _value))
                return _value;

            return default(T);
        }

        public bool Set<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (expiresIn.HasValue)
                _cache.Set(key, value, new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(expiresIn.Value.TotalSeconds)
                });
            else
                _cache.Set(key, value);

            return true;
        }

        public bool Exists(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            return _cache.TryGetValue(key, out _);
        }


        public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
        {
            var map = new Dictionary<string, T>();

            foreach (string key in keys)
                map[key] = Get<T>(key);

            return map;
        }

        public int SetAll<T>(IDictionary<string, T> values, TimeSpan? expiresIn = null)
        {
            if (values == null || values.Count == 0)
                return 0;

            var list = new List<bool>();

            foreach (var entry in values)
                list.Add(Set(entry.Key, entry.Value, expiresIn));

            return list.Count(r => r);
        }


        /// <summary>
        /// Adds the services.
        /// </summary>
        /// <param name="services">Services.</param>
        public void AddServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure(_name, configure);
            services.AddSingleton<IInMemoryCaching, InMemoryCaching>(x =>
            {
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(_name);
                return new InMemoryCaching(_name, options.DBConfig);
            });

            services.TryAddSingleton<IEasyCachingProviderFactory, DefaultEasyCachingProviderFactory>();
            services.AddSingleton<IEasyCachingProvider, DefaultInMemoryCachingProvider>(x =>
            {
                var mCache = x.GetServices<IInMemoryCaching>();
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(_name);
                var dlf = x.GetService<IDistributedLockFactory>();
                // ILoggerFactory can be null
                var factory = x.GetService<Microsoft.Extensions.Logging.ILoggerFactory>();
                return new DefaultInMemoryCachingProvider(_name, mCache, options, dlf, factory);
            });
        }


        public bool Add<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (Exists(key))
                return false;
            Set(key, value, expiresIn);
            return true;
        }

        public T Get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (_cache.TryGetValue(key, out T _value))
                return _value;

            return default(T);
        }

        public bool Set<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            if (expiresIn.HasValue)
                _cache.Set(key, value, new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(expiresIn.Value.TotalSeconds)
                });
            else
                _cache.Set(key, value);

            return true;
        }

        public bool Exists(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException(nameof(key));

            return _cache.TryGetValue(key, out _);
        }


        public IDictionary<string, T> GetAll<T>(IEnumerable<string> keys)
        {
            var map = new Dictionary<string, T>();

            foreach (string key in keys)
                map[key] = Get<T>(key);

            return map;
        }

        public int SetAll<T>(IDictionary<string, T> values, TimeSpan? expiresIn = null)
        {
            if (values == null || values.Count == 0)
                return 0;

            var list = new List<bool>();

            foreach (var entry in values)
                list.Add(Set(entry.Key, entry.Value, expiresIn));

            return list.Count(r => r);
        }

using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("InMemoryCaching")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InMemoryCaching")]
[assembly: AssemblyCopyright("Copyright ©  2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("12f79162-c714-4613-b6b4-c5d92914b336")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

        /// <summary>
        /// Uses the in memory.
        /// </summary>
        /// <returns>The in memory.</returns>
        /// <param name="options">Options.</param>
        /// <param name="configuration">Configuration.</param>
        /// <param name="name">Name.</param>
        /// <param name="sectionName">SectionName.</param>
        public static IServiceCollection AddMemoryServices(this IServiceCollection services, IConfiguration configuration, string name = CachingConstValue.DefaultInMemoryName, string sectionName = CachingConstValue.InMemorySection)
        {
            var dbConfig = configuration.GetSection(sectionName);
            var memoryOptions = new InMemoryOptions();
            dbConfig.Bind(memoryOptions);

            //void configure(InMemoryOptions x)
            //{
            //    x.CachingProviderType = memoryOptions.CachingProviderType;
            //    x.EnableLogging = memoryOptions.EnableLogging;
            //    x.MaxRdSecond = memoryOptions.MaxRdSecond;
            //    x.Order = memoryOptions.Order;
            //    x.DBConfig = memoryOptions.DBConfig;
            //}
            return AddMemoryServices(services,x=> {
                x.CachingProviderType = memoryOptions.CachingProviderType;
                x.EnableLogging = memoryOptions.EnableLogging;
                x.MaxRdSecond = memoryOptions.MaxRdSecond;
                x.Order = memoryOptions.Order;
                x.DBConfig = memoryOptions.DBConfig;
            }, name);
        }
        /// <summary>
        /// Adds the services.
        /// </summary>
        /// <param name="services">Services.</param>
        public static IServiceCollection AddMemoryServices(this IServiceCollection services, Action<InMemoryOptions> configure, string name = CachingConstValue.DefaultInMemoryName)
        {
            services.AddOptions();
            services.Configure(name, configure);
            services.AddMemoryCache();
            services.AddSingleton<IInMemoryCaching, InMemoryCaching>(x =>
            {
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(name);
                IMemoryCache memoryCache=x.GetRequiredService<IMemoryCache>();
                return new InMemoryCaching(name, options.DBConfig,memoryCache);
            });
            services.TryAddSingleton<ICachingProviderFactory, DefaultCachingProviderFactory>();
            services.AddSingleton<ICachingProvider, DefaultInMemoryCachingProvider>(x =>
            {
                var mCache = x.GetServices<IInMemoryCaching>();
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(name);
                //ILoggerFactory can be null
                var factory = x.GetService<Microsoft.Extensions.Logging.ILoggerFactory>();
                return new DefaultInMemoryCachingProvider(name, mCache, options, factory);
            });
            return services;

        }


        public void Clear(string prefix = "")
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {                
                _memory.Clear();

                if (_options.SizeLimit.HasValue)
                    Interlocked.Exchange(ref _cacheSize, 0);
            }
            else
            {
                RemoveByPrefix(prefix);
            }
        }

        public int GetCount(string prefix = "")
        {
            return string.IsNullOrWhiteSpace(prefix)
                ? _memory.Count
                : _memory.Count(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
        }

        internal void RemoveExpiredKey(string key)
        {
           bool flag = _memory.TryRemove(key, out _);
            if (_options.SizeLimit.HasValue && flag)
                Interlocked.Decrement(ref _cacheSize);
        }

        public CacheValue<T> Get<T>(string key)
        {
            ArgumentCheck.NotNullOrWhiteSpace(key, nameof(key));

            if (!_memory.TryGetValue(key, out var cacheEntry))
            {
                return CacheValue<T>.NoValue;
            }

            if (cacheEntry.ExpiresAt < SystemClock.UtcNow)
            {
                RemoveExpiredKey(key);
                return CacheValue<T>.NoValue;
            }

            try
            {
                var value = cacheEntry.GetValue<T>(_options.EnableReadDeepClone);
                return new CacheValue<T>(value, true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"some error herer, message = {ex.Message}");
                return CacheValue<T>.NoValue;
            }
        }

        public object Get(string key)
        {
            ArgumentCheck.NotNullOrWhiteSpace(key, nameof(key));

            if (!_memory.TryGetValue(key, out var cacheEntry))
            {
                return null;
            }

            if (cacheEntry.ExpiresAt < SystemClock.UtcNow)
            {
                RemoveExpiredKey(key);
                return null;
            }

            try
            {
                return cacheEntry.Value;
            }
            catch
            {
                return null;
            }
        }

        public bool Add<T>(string key, T value, TimeSpan? expiresIn = null)
        {
            ArgumentCheck.NotNullOrWhiteSpace(key, nameof(key));

            var expiresAt = expiresIn.HasValue ? SystemClock.UtcNow.SafeAdd(expiresIn.Value) : DateTimeOffset.MaxValue;
            return SetInternal(new CacheEntry(key, value, expiresAt), true);
        }


        /// <summary>
        /// Adds the services.
        /// </summary>
        /// <param name="services">Services.</param>
        public void AddServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure(_name, configure);
            services.AddSingleton<IInMemoryCaching, InMemoryCaching>(x =>
            {
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(_name);
                return new InMemoryCaching(_name, options.DBConfig);
            });

            services.TryAddSingleton<IEasyCachingProviderFactory, DefaultEasyCachingProviderFactory>();
            services.AddSingleton<IEasyCachingProvider, DefaultInMemoryCachingProvider>(x =>
            {
                var mCache = x.GetServices<IInMemoryCaching>();
                var optionsMon = x.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<InMemoryOptions>>();
                var options = optionsMon.Get(_name);
                var dlf = x.GetService<IDistributedLockFactory>();
                // ILoggerFactory can be null
                var factory = x.GetService<Microsoft.Extensions.Logging.ILoggerFactory>();
                return new DefaultInMemoryCachingProvider(_name, mCache, options, dlf, factory);
            });
        }

EasyCaching.InMemory.InMemoryCaching : IInMemoryCaching

Constructors :

public InMemoryCaching(String name = , InMemoryCachingOptions optionsAccessor = )

Methods :

public String get_ProviderName()
public Void Clear(String prefix = )
public Int32 GetCount(String prefix = )
public CacheValue<T> Get(String key = )
public Object Get(String key = )
public Boolean Add(String key = , T value = , Nullable<TimeSpan> expiresIn = null)
public Boolean Set(String key = , T value = , Nullable<TimeSpan> expiresIn = null)
public Boolean Exists(String key = )
public Int32 RemoveAll(IEnumerable<String> keys = null)
public Boolean Remove(String key = )
public Int32 RemoveByPrefix(String prefix = )
public IDictionary<String, CacheValue<T>> GetAll(IEnumerable<String> keys = )
public Int32 SetAll(IDictionary<String, T> values = , Nullable<TimeSpan> expiresIn = null)
public Boolean Replace(String key = , T value = , Nullable<TimeSpan> expiresIn = null)
public IDictionary<String, CacheValue<T>> GetByPrefix(String key = )
public TimeSpan GetExpiration(String key = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()