Writing a json resource reader in .NET Core
We're going to create a custom Resource reader to use with .NET Core libraries.
Category Funtamentals
Published: 23 July 2021
In this post, we're going to create a custom Resource reader to use with .NET Core libraries. In the end, we can have a project dedicated to resources.
First, we need a class that represents our json
file:
The Key
is an unique identifier for the localization and LocalizedValues
is a dictionary, which its key is the language and the value the text that must be displayed.
We also going to create a new type of Exception
, to easily pinpoint what went wrong with the application.
Here is where the magic happens, the JsonLocalizer
class will read our json resources files
, store them in memory and make them available to our application.
In our constructor we expect two parameters, useBase
and additionalPaths
.
If useBase
is set to true, the localizer will load *.json
files that are in the Resources
folder.additionalPaths
uses a type as a key, the localizer will use this type to find the assembly path and read the *.json
files in the Resources
folder.
In dotnet core
applications, you can add the JsonLocalizer
using the IServiceCollection
in the ConfigureServices
method.
To handle additionalPaths
Now that we have everything set up, we can start using our localizer:
The Localizer will find your text by:
FileName:Key:Language
Here are some examples of how to write your resource files:
File Name | Resource Name |
---|---|
MyResource.json | MyResource |
MyApp.Resource.json | MyApp |
MyApp-Errors.Resource.json | MyApp-Errors |
MyApp.Errors.Resource.json | MyApp |
The Key
is the key inside the resource file, and the Language
is the culture, if not informed, will use the CultureInfo.CurrentCulture
value.
The json
resource file should follow this format: