这是我的代码:
public class RouteSingleton
{
private IDictionary<string, string> _dealCatLinks;
private IDictionary<string, string> _sectionLinks;
private IDictionary<string, string> _categoryLinks;
private IDictionary<string, string> _materials;
private IDictionary<string, string> _vendors;
public RouteSingleton(IDealService dealService
, ICategoryService categoryService
, IVendorService vendorService)
{
this._dealCatLinks = dealService.GetDealCatLinks("PLV").Distinct().ToDictionary(x => x, x => x);
this._sectionLinks = categoryService.GetSectionLinks("PLV").Distinct().ToDictionary(x => x, x => x);
this._categoryLinks = categoryService.GetMainCategoryLinks("PLV")
.Where(x => !_sectionLinks.ContainsKey(x)).Distinct().ToDictionary(x => x, x => x);
this._vendors = _vendorService.GetVendorLinks("PFB").Distinct().ToDictionary(x => x, x => x);
}
public bool IsDealCategory(string slug)
{
return _dealCatLinks.ContainsKey(slug);
}
public bool IsSectionUrl(string slug)
{
return _sectionLinks.ContainsKey(slug);
}
public bool IsCategory(string slug)
{
return _categoryLinks.ContainsKey(slug);
}
public bool IsVendor(string slug)
{
return _vendors.ContainsKey(slug);
}
}
以下是我在startup.cs
注册的方式:
services.AddSingleton<RouteSingleton, RouteSingleton>();
我使用singleton
中的route constraints
就像这样:
routes.MapRoute("category", "{slug}", defaults: new { controller = "Category", action = "Index" }, constraints: new { slug = new CategoryConstraint(app.ApplicationServices.GetRequiredService<RouteSingleton>()) });
lock threads
RouteSingleton.cs
或我的代码在应用程序启动时会在很多用户下正常工作吗?答案 0 :(得分:6)
不,你不需要锁定任何东西。它是一个单独的,只能构造一次,而你在多个线程中同时使用私有字典进行的唯一事情就是调用ContainsKey
,这应该是非常安全的,因为当你还没有别的东西可以修改字典致电ContainsKey
。
但是,如果你在构造函数之后修改这些字典,那将是一个完全不同的故事 - 你要么必须使用锁/互斥锁等。保护对它们的访问或使用线程安全字典,例如ConcurrentDictionary
。正如目前所写,你应该没事。