【发布时间】:2019-07-27 13:09:53
【问题描述】:
我正在重新设计一个 ASP.NET CORE 2.2 应用程序,以避免将服务定位器模式与静态类结合使用。双坏!
重新工具涉及创建和注入 Singleton 对象作为一些全局数据的存储库。这里的想法是避免在请求中反复使用一些基本/全局数据对我的 SQL 服务器造成影响。但是,这些数据需要每小时更新一次(不仅仅是在应用程序启动时)。因此,为了管理这种情况,我使用 SemaphoreSlim 来处理对数据对象的一次访问。
这是我正在做的事情的配对草图:
namespace MyApp.Global
{
public interface IMyGlobalDataService
{
Task<List<ImportantDataItem>> GetFilteredDataOfMyList(string prop1);
Task LoadMyImportantDataListAsync();
}
public class MyGlobalDataService: IMyGlobalDataService
{
private MyDbContext _myDbContext;
private readonly SemaphoreSlim myImportantDataLock = new SemaphoreSlim(1, 1);
private List<ImportantDataItem> myImportantDataList { get; set; }
public async Task<List<ImportantDataItem>> GetFilteredDataOfMyList(string prop1)
{
List<ImportantDataItem> list;
myImportantDataLock.WaitAsync();
try
{
list = myImportantDataList.Where(itm => itm.Prop1 == prop1).ToList();
}
finally
{
myImportantDataLock.Release();
}
return list;
}
public async Task LoadMyImportantDataListAsync()
{
// this method gets called when the Service is created and once every hour thereafter
myImportantDataLock.WaitAsync();
try
{
this.MyImportantDataList = await _myDbContext.ImportantDataItems.ToListAsync();
}
finally
{
myImportantDataLock.Release();
}
return;
}
public MyGlobalDataService(MyDbContext myDbContext) {
_myDbContext = myDbContext;
};
}
}
所以实际上我使用 SemaphoreSlim 来限制一次一个线程的访问,用于读取和更新到 myImportantDataList。这对我来说真的是一个不确定的领域。这似乎是处理我在整个应用程序中注入全局数据单例的合适方法吗?或者我应该期待疯狂的线程锁定/阻塞?
【问题讨论】:
标签: c# dependency-injection singleton semaphore asp.net-core-2.2