环境:net core 6.0
builder.Services.AddMemoryCache();
builder.Services.AddTransient<MemoryCacheService>();
ICacheService cacheMemory;
//控制器构造函数中得到服务
public WorkFlowController(IServiceProvider service) {
cacheMemory = service.GetService<MemoryCacheService>();
}
其他用法,比如如何在业务层实例化缓存
public static class ServiceLocator
{
/// <summary>
/// 服务提供程序,用于直接获取已注入的类
/// </summary>
public static IServiceProvider ServiceProvider { get; set; }
public static IApplicationBuilder ApplicationBuilder { get; set; }
}
var app = builder.Build();
ServiceLocator.ApplicationBuilder = app;
ServiceLocator.ServiceProvider = app.Services;
//实例化对象
var cache = ServiceLocator.ServiceProvider.GetService(typeof(MemoryCacheService)) as ICacheService;
public interface ICacheService
{
/// <summary>
/// 新增
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="ExpirtionTime"></param>
/// <returns></returns>
bool Add(string key, object value, int ExpirtionTime = 20);
/// <summary>
/// 获取
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object GetValue(string key);
/// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
bool Exists(string key);
/// <summary>
/// 移除
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
bool Remove(string key);
}
public class MemoryCacheService : ICacheService
{
protected IMemoryCache _cache;
public MemoryCacheService(IMemoryCache cache)
{
_cache = cache;
}
public bool Add(string key, object value, int ExpirtionTime = 20)
{
if (!string.IsNullOrEmpty(key))
{
MemoryCacheEntryOptions cacheEntityOps = new MemoryCacheEntryOptions()
{
//滑动过期时间 20秒没有访问则清除
SlidingExpiration = TimeSpan.FromSeconds(ExpirtionTime),
//设置份数
Size = 1,
//优先级
Priority = CacheItemPriority.Low,
};
//过期回掉
cacheEntityOps.RegisterPostEvictionCallback((keyInfo, valueInfo, reason, state) =>
{
Console.WriteLine($"回调函数输出【键:{keyInfo},值:{valueInfo},被清除的原因:{reason}】");
});
_cache.Set(key, value, cacheEntityOps);
}
return true;
}
public bool Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
if (Exists(key))
{
_cache.Remove(key);
return true;
}
return false;
}
public object GetValue(string key)
{
if (string.IsNullOrEmpty(key))
{
return null;
}
if (Exists(key))
{
return _cache.Get(key);
}
return null;
}
public bool Exists(string key)
{
if (string.IsNullOrEmpty(key))
{
return false;
}
object cache;
return _cache.TryGetValue(key, out cache);
}
}
说明:如果使用的自带的IMemoryCache,只需要builder.Services.AddMemoryCache();即可