简体   繁体   中英

How to provide localized resources for a nuget package?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM