Search code examples
c#asp.net.netlocalization

How can I put a file in cache in dotnet?


I have been trying to implement localization in .NET 6.0 via JSON files, and a way of doing that (please note that the resources are provided as JSONs with different formats eg one has nested objects and the other simply key-values) was to implement the IStringLocalizer interface and of course every time on lookup in something doesn't exist in the IDistributedCache then load the file, parse it accordingly and insert the key-value pair in the distributed cache.

However, upon every entry that doesn't exist in the distributed cache, I will have to load the file (which is IO lookup and I am guessing rather expensive for the app, especially if there is a cache miss frequently) and get the value depending from which file I want to read from.

Is there a way to load the file when startup is called and simply inject it to the localizer extension that I have made?


Solution

  • You can invoke your service which manage localization in Startup like that

    app.Services.GetService<IMyLocalizationService>().LoadLocalization()
    

    In that moment DI should be builded so you should have access to IDistributedCache