Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to lock singleton in ASP.NET Core?

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>()) });
  1. I wonder do I need to lock threads in my RouteSingleton.cs or my code will work fine under lots of users on application start?
  2. If I need to lock what way you can suggest to me?
  3. What will happen if I don't?
like image 231
Alex Gurskiy Avatar asked Aug 05 '17 23:08

Alex Gurskiy


1 Answers

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.

like image 99
Tim Avatar answered Oct 22 '22 07:10

Tim