如何解析singleton对象内部的作用域服务



我有MemoryCache对象(应用程序、配置等(,我将它们注册为Singleton。还有一些作用域存储库,它们从数据库中选择数据来填充缓存。

例如,这里是Singleton注册的类,

public class ApplicationCache : MultipleLoadCache<Application>
{
public ApplicationCache() 
{

}
}

MultipleLoadCache覆盖CacheItemPolicy,(还有SingleLoadCache(,

public class MultipleLoadCache<TEntity> : SmartCache<TEntity> where TEntity : class
{
public MultipleLoadCache()
{
}
protected override CacheItemPolicy SetPolicy()
{
return new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(15)
};
}
}

基本类是

public class SmartCache<TEntity> : IDisposable where TEntity : class
{
public bool TryGetList(IRepository<TEntity> repository, out List<TEntity> valueList)
{
valueList = null;
lock (cacheLock)
{
GenerateCacheIfNotExists(repository, out valueList);
if (valueList == null || valueList.Count == 0)
{
valueList = (List<TEntity>)_memoryCache.Get(key);
}
}
return valueList != null;
}

我知道作用域服务不能注入到singleton类中。所以我更喜欢使用方法注射。

private void GenerateCacheIfNotExists(IRepository<TEntity> repository, out List<TEntity> list)
{
list = null;
if (!_memoryCache.Any(x => x.Key == key)) // if key not exists, get db records from repo.
{
IEnumerable<TEntity> tempList = repository.GetList();
list = tempList.ToList();
_cacheItemPolicy = SetPolicy();
SetCacheList(list);
}
}
}

在控制器上,我试图获取缓存值,但这部分对我来说似乎是错误的。如果我试图获取高速缓存值,我不应该将repository作为参数传递。

private readonly ApplicationCache _appCache;
public LogController(ApplicationCache appCache)
{
_appCache = appCache;
}
[HttpPost]
[Route("Register")]
public List<Application> Register([FromServices] IApplicationRepository repository)
{
List<Application> cf;
_appCache.TryGetList(repository, out cf);
return cf;
}

此外,通过执行方法注入。我也无法使用CacheItemPolicyRemovedCallBack事件。因为,当回调触发(重新加载缓存(时,我需要存储库来再次从数据库中获取记录。

这个设计看起来不错吗?使用MemoryCache的回调事件做这件事的最佳设计是什么?

更新1-

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMemoryCache();
services.AddSingleton(x => new ApplicationCache());
services.AddScoped<IApplicationRepository, ApplicationRepository>();
}

谢谢,

我遇到了同样的问题。由于静态类是在开始时编译的,因此以后无法注入所需的服务。我通过使用IServiceScopeFactory找到了它。

您基本上将IServiceScopeFactory serviceScopeFactory注入到构造函数中。

static SampleClass(IServiceScopeFactory serviceScopeFactory){  
//serviceScopedFactory will act as Singleton, since it is a static class
_serviceScopeFactory = serviceScopeFactory;
}

在方法中这样使用:

using (var scope = _serviceScopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IService>();
//Here you can use the service. This will be used as Scoped since it will be 
//recreated everytime it is called

}

最新更新