Home > front end >  How to provide localized resources for a nuget package?
How to provide localized resources for a nuget package?

Time:01-28

I'm looking for a way to allow consumers of a NuGet package to provide their own localization for a string returned to an HTTP API caller (through ASP.NET Core middleware). The class is called ApiKeyAuthenticationHandler and I'm using an IStringLocalizer<ApiKeyAuthenticationHandler>.

On the client app (that consumes the package), I've tried to have:

  • Resources\ApiKeyAuthenticationHandler.resx
  • Resources\NugetPackageNamespace.ApiKeyAuthenticationHandler.resx
  • Resources\Nuget\Package\Namespace\ApiKeyAuthenticationHandler.resx

Also included the .es.resx variants to see if different languages are picked up (client app configured as documentation states), but, those are all ignored.

If I add a Resources\ApiKeyAuthenticationHandler.resx file to the NuGet package project itself, then I get that string but not the ones specified in the client app.

How can I achieve this so that the client is the one that creates the resources, as this is a public package and I do not want to force any values/languages?

CodePudding user response:

It turns out that when you request an IStringLocalizer from DI, the type's assembly is what is used to get the resources.

This can be achieved by going a step lower and using an IStringLocalizerFactory:

var assembly = Assembly.GetEntryAssembly()!;
var assemblyName = new AssemblyName(assembly.FullName!);
var localizer = _stringLocalizerFactory.Create(nameof(ApiKeyAuthenticationHandler), assemblyName.Name!);

The second parameter, even though it's called location, asks for the name of the assembly that contains the .resx files - which in this case is the entry assembly.

In the client app, resources can be just added to the main Resources folder (Resources\ApiKeyAuthenticationHandler.resx)

  • Related