How to access global resources for localization in a class library?

I have an asp.net site (not a web application) and I localized the text for the user interface using resource files (.resx). I also have a class library that contains business logic, and there is a validation method that returns an error message. I need to localize this error message, but cannot find a way to access the global resource file on my website. On a website, let's say in code, I can use Resources.LocalisedText.MyErrorMessage (where LocalisedText is the name of my LocalisedText.resx resource file). However, in my class library I cannot get a link to it.

I found this link http://weblogs.asp.net/rinze/archive/2008/12/03/using-globalization-resources-resx-in-a-class-library-or-custom-control.aspx in which says it can be done, but it doesn't seem to work for me, probably because I cannot get the correct namespace for the website?

+6
localization
source share
2 answers

I managed to get this to work based on the resx constructor file. If you open it and look at the ResourceManager property get attribute, you can simply copy the line to access the same resources.

Full explanation

First of all, you need to open the resource file .designer.cs . This should be in your solution explorer, as in the following image:

Resource file designer file location in solution explorer

Just double-click it to open it, and then scan it (it should be near the top):
internal static global::System.Resources.ResourceManager ResourceManager {

In the get accessory, you should see that it assigns something to the temp variable. In my case, it looked like this:

 /*...*/ temp = new global::System.Resources.ResourceManager("Resources.Lang", global::System.Reflection.Assembly.Load("App_GlobalResources")); 

So, based on this, I created a ResourceManager in a class that I wanted to use in my class library, for example:

 ResourceManager lang = new ResourceManager("Resources.Lang", Assembly.Load("App_GlobalResources")); 

Note 1: Remember to add using System.Resources; and using System.Reflection; to the beginning of the file.
Note 2: This does not require adding a link to a web project in the class library.

Then I just call the GetString method in my lang variable to get the resources I need.
For example. lang.GetString("MyErrorMessage") .
It is not as elegant as calling Resources.Lang.MyErrorMessage , but it does its job.

Hope this helps. If you have any questions, write a comment below.

+4
source share
 new ResourceManager("YourRessourceName", Assembly.GetEntryAssembly()).GetString("MyLocalizedString"); 

here you create a ressourceManager using the execution assembly (your website), "YourRessourcenName" is the name of your ressource file without resx and language.

0
source share

All Articles