[英]Injecting scoped service from singleton service in .net core 2.1
我有一個cacheHelper。 當我將CacheHelper的依賴項添加到使用“ AddScoped”啟動時,它正在工作。 但是, CacheHelper.cs
正在為每個請求運行。 因此,我將如下所示轉換為“ AddSingleton”。 但是我遇到了這樣的錯誤: 無法使用單例“ MyProject.Caching.ICacheHelper”中的作用域服務“ MyProject.DataAccess.IUnitOfWork”如何解決此問題?
Strartup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IJwtHelper, JwtHelper>();
services.AddScoped<IAuditHelper, AuditHelper>();
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
services.AddSingleton<ICacheHelper, CacheHelper>();
services.AddMvc();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
CacheHelper.cs
public class CacheHelper : ICacheHelper
{
private readonly IUnitOfWork unitOfWork;
public IMemoryCache Cache { get; }
public CacheHelper(IUnitOfWork unitOfWork, IMemoryCache cache)
{
this.unitOfWork = unitOfWork;
Cache = cache;
}
public void SetCommonCacheItems()
{
var cities = unitOfWork.CityRepo.GetAll();
Cache.Set("cities", cities);
string obj;
Cache.TryGetValue<string>("cities", out obj);
}
public string GetCities()
{
string obj;
Cache.TryGetValue<string>("cities", out obj);
return obj;
}
}
您以前擁有它的方式是正確的。 ICacheHelper
應該並且必須進行范圍ICacheHelper
。
只是您的緩存實現是錯誤的。 獲取城市將被調用,它檢查緩存。 如果找不到,它將獲取數據並將其放入緩存。
public class CacheHelper : ICacheHelper
{
private readonly IUnitOfWork unitOfWork;
public IMemoryCache Cache { get; }
public CacheHelper(IUnitOfWork unitOfWork, IMemoryCache cache)
{
this.unitOfWork = unitOfWork;
Cache = cache;
}
public string GetCities()
{
if(!Cache.TryGetValue<string>("cities", string out cities))
{
// not found in cache, obtain it
cities = unitOfWork.CityRepo.GetAll();
Cache.Set("cities", cities);
}
return cities;
}
}
您不需要SetCommonCacheItems()
方法。 重要的是IMemoryCache
是靜態的,因為它將包含數據。 由於數據庫的原因,必須限制UoW的范圍,否則您將發生內存泄漏(尤其是在使用EF Core時,因為它緩存/跟蹤實體)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.