netCore自定义接口依赖注入DI定义接口ICacheUtil.csnamespace Snblog.Cache.CacheUtil{public interface ICacheUtil{/// summary/// 设置并返回缓存值(值类型)/// /summary/// typeparam name=T返回类型...
netCore自定义接口依赖注入DI
定义接口
ICacheUtil.cs
namespace Snblog.Cache.CacheUtil
{
public interface ICacheUtil
{
/// <summary>
/// 设置并返回缓存值(值类型)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="key">缓存键值</param>
/// <param name="value">要缓存的值</param>
/// <returns>result</returns>
public T CacheNumber<T>(string key, T value);
/// <summary>
/// 设置并返回缓存值(字符串)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="key">缓存键值</param>
/// <param name="value">要缓存的值</param>
public T CacheString<T>(string key, T value);
}
}
继承接口
using Snblog.Cache.Cache;
namespace Snblog.Cache.CacheUtil
{
public class CacheUtil:ICacheUtil
{
//创建内存缓存对象
private static CacheManager _cache = new CacheManager();
/// <summary>
/// 设置并返回缓存值(值类型)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="key">缓存键值</param>
/// <param name="value">要缓存的值</param>
/// <returns>result</returns>
public T CacheNumber<T>(string key, T value)
{
T result = default;
if (_cache.IsInCache(key)) //如果存在缓存取值
{
result = _cache.Get<T>(key);
}
else
{
if (!value.Equals(0))
{
_cache.Set_AbsoluteExpire<T>(key, value, _cache.time);
}
}
return result;
}
/// <summary>
/// 设置并返回缓存值(字符串)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="key">缓存键值</param>
/// <param name="value">要缓存的值</param>
public T CacheString<T>(string key, T value)
{
T result = default;
if (_cache.IsInCache(key)) //如果存在缓存取值
{
result = _cache.Get<T>(key);
}
else
{
if (value != null)
{
_cache.Set_AbsoluteExpire<T>(key, value, _cache.time);
}
}
return result;
}
}
}
DI依赖注入配置
ConfigureServices
services.AddScoped<ICacheUtil,CacheUtil>();
使用
private readonly CacheUtil _cacheUtil;
public SnArticleService(ICacheUtil cacheUtil,IRepositoryFactory repositoryFactory, IconcardContext mydbcontext, snblogContext coreDbContext, ILogger<SnArticleService> logger) : base(repositoryFactory, mydbcontext)
{
_coreDbContext = coreDbContext;
_cacheUtil= (CacheUtil)cacheUtil;
_logger = logger ?? throw new ArgumentNullException(nameof(Logger));
}
result = _cacheUtil.CacheString("AsyGetTestName" + id, result);
沃梦达教程
本文标题为:netCore自定义接口依赖注入DI
基础教程推荐
猜你喜欢
- unity实现动态排行榜 2023-04-27
- winform把Office转成PDF文件 2023-06-14
- ZooKeeper的安装及部署教程 2023-01-22
- C# List实现行转列的通用方案 2022-11-02
- C# windows语音识别与朗读实例 2023-04-27
- C# 调用WebService的方法 2023-03-09
- C#类和结构详解 2023-05-30
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- 一个读写csv文件的C#类 2022-11-06
- C#控制台实现飞行棋小游戏 2023-04-22