【发布时间】:2018-10-25 06:53:30
【问题描述】:
我有一个缓存助手。当我将 CacheHelper 的依赖项添加到使用“AddScoped”启动时,它正在工作。但是,CacheHelper.cs 正在为每个请求运行。所以,我转换为“AddSingleton”,如下所示。但我犯了一个错误,就像这样:
无法使用单例“MyProject.Caching.ICacheHelper”中的范围服务“MyProject.DataAccess.IUnitOfWork”如何解决此问题?
启动.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;
}
}
【问题讨论】:
-
值得您花时间阅读:dotnetcoretutorials.com/2018/03/20/…
-
Singleton 不能引用 Scoped 实例
-
谢谢@JohnB。我现在读了你的帖子。在那篇文章中,它建议我将 unitOfWork 添加为单例。但是当我将 UnitOfWork 作为单例进行时,我的请求并没有发送到服务器。哪里会出错?
标签: c# asp.net-web-api asp.net-core .net-core