Is it advisable to use a .resx file to store common string references in a class library?

StackOverflow https://stackoverflow.com/questions/12410162

  •  01-07-2021
  •  | 
  •  

Pregunta

Is it advisable to use a .resx file to store common string references in a business layer class library? I typically only ever see these been used in the presentation layer.

¿Fue útil?

Solución

One option to be to have a separate project in your solution, which has all the resx files for your whole solution. You can then add it as a reference to your business layer. In the Resources Project, you can write a wrapper around .net ResourceManager class, to return the resource value for your key. Something on the lines of:

public class ResourceService : IResourceService
{
    public ResourceService() {}

    public GetResourceValue(string resourceFileName, string resourceKey)
    {
         var resourceManager = new ResourceManager("Myresources", Assembly.Load("MyResourcesProjectName"));
         return resourceManager.GetString(resourceKey);
    }
} 

Then you can use it from you business layer as:

var resourceService = new ResourceService();
var resourceValue = resourceService.GetResourceValue("MyResources", "ResourceKeyName");

I did not have time to test the code, I have written on the fly, but it should give you the general idea. IMO, there is nothing wrong in having the resx files in a separate project. Another way of approaching it, is to have .resx file in places where they are used. I find the separate project idea better, because that way, you can create separate folder for each type of language, and store locale specific .resx files in it.

Otros consejos

It's best to try to move strings that the user will see up to the presentation layer, but it isn't uncommon to have to build some messages in the business layer. If you are planning on translating the messages to multiple languages/cultures then it is appropriate to put them in a resx file.

I see no problem with putting user-facing strings into resx file on any layer.

I.e. if you business logic have something like CreateGreatingMail(User user, CultureInfo language) than you will have multiple user-facing localize-able strings that you need to put somewhere and resx is the best place.

For sharing UI strings you can have explicit UI layer assembly solely dedicated to UI strings instead of merging it into shared business layer.

Yes Exaclty .resx file is placed on Presentation Layer.

But you can set constant

const string toto = "test";
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top