Jaska
Jaska

Reputation: 1037

ASP.NET Core data annotation localization when models are in a different assembly

I have ASP.NET Core 3.0 Razor Pages application. Localization works fine as long as all the code is in the main assembly. However if I move my model classes into another library assembly data annotation localization does not work anymore.

How to configure localization in this case? Where to place the .resx files? In the resources folder of the main assembly or somewhere in the library assembly. How should I name the resource files?

public class Message
{
  [Display(Name = "ID")]
  public int Id { get; set; }

  [Display(Name = "Message text")]
  public string Text { get; set; }

  [Display(Name = "Create date")]
  public DateTime Created { get; set; }
}

This Message class is in a different assembly. Here is m current configuration.

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<MessageService, MessageService>();

  services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

  services.AddRazorPages()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();
}

Upvotes: 2

Views: 1295

Answers (1)

Steve Newton
Steve Newton

Reputation: 1078

I have got this to work after many hours, I used this as the base:

https://dejanstojanovic.net/aspnet/2019/april/localization-of-the-dtos-in-a-separate-assembly-in-aspnet-core/

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-3.1

I updated it to go against services.AddRazorPages() not .AddMVC as required in the latest versions. I am now able to have the Resources folder in both the main library which I implement the standard solution, which is used for view localisation, and the Class Library which is used for Models etc, like your message class.

Upvotes: 2

Related Questions