我正在.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);
它告诉我,我没有将参数传递给缓存构造函数。
答案 0 :(得分:4)
由于您正在使用DI,请避免完全使用new
。
让您的课程Cache
实现一个接口,例如:
public interface ICache
{
void Add(string key, byte[] value, int expiration);
}
public class Cache : ICache
{
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);
}
}
在您的容器中将Cache
注册为ICache
。 AutoFac示例:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Cache>().As<ICache>();
然后在需要使用Cache
对象的类中,将其作为依赖项注入:
class ClassThatNeedsACache
{
ICache _cache;
ClassThatNeedsACache(ICache cache)
{
_cache = cache;
}
void MethodThatUsesACache()
{
// Some other code to create your encodedCurrentTimeUTC and expiration
_cache.Add("time", encodedCurrentTimeUTC, expiration);
}
}
依赖注入框架将所有内容组合到您的合成根目录中,例如ASP.NET中的Global.asax,并维护应用程序中对象的创建和生存期。