【发布时间】:2019-01-14 23:23:44
【问题描述】:
我正在 .net core 2.2 中创建一个助手,用于缓存到 Redis。当我调用 Add 方法时,它不会通过我的构造函数来创建 IDistributedCache 实例。
public class Cache
{
public static IDistributedCache _cache;
public Cache(IDistributedCache cache)
{
_cache = cache;
}
public static void Add(string key, byte[] value, int expiration)
{
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(expiration));
_cache.Set(key, value, options);
}
}
我不完全理解我错过了什么。我这样称呼方法
Cache.Add("time", encodedCurrentTimeUTC, expiration);
编辑: 我已经删除了静态条目
public class Cache
{
public IDistributedCache _cache;
public Cache(IDistributedCache cache)
{
_cache = cache;
}
public void Add(string key, byte[] value, int expiration)
{
var options = new DistributedCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(expiration));
_cache.Set(key, value, options);
}
}
但是当我尝试调用该方法时
var newItem = new Cache();
newItem.Add("time", encodedCurrentTimeUTC, expiration);
它告诉我我没有将参数传递给缓存构造函数。
【问题讨论】:
-
你的
Add方法是静态的,所以我认为你的构造函数不会被调用。 -
你没有打电话给
new Cache -
@User 问题是静态构造函数不能包含参数 - 它们从哪里来?
-
@User 你确定静态构造函数是合适的吗?应该经常避免使用静态类。最好使用该类的单个实例,然后向 IoC 容器注册单个实例。
-
@User 好吧,如果您要提出解决问题的方法,最好先考虑一下。如果您不确定这是一个好主意,请让其他人提供帮助。
标签: c# asp.net-core