Here is my code:
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);
}
}
Here is how I register in startup.cs
:
services.AddSingleton<RouteSingleton, RouteSingleton>();
And I use the singleton
in route constraints
like so:
routes.MapRoute("category", "{slug}", defaults: new { controller = "Category", action = "Index" }, constraints: new { slug = new CategoryConstraint(app.ApplicationServices.GetRequiredService<RouteSingleton>()) });
lock threads
in my RouteSingleton.cs
or my code will work fine under lots of users on application start?No, you don't need to lock anything. It is a singleton and will only be constructed once, and the only thing you are doing with your private dictionaries in multiple threads simultaneously is calling ContainsKey
, which should be quite safe since nothing else can be modifying the dictionary while you are calling ContainsKey
.
However, if you were modifying those dictionaries after the constructor, it would be an entirely different story-- you would either have to use a lock/mutex/etc. to protect access to them or use a thread safe dictionary, such as ConcurrentDictionary
. As it is currently written, you should be fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With