Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global resources for localization in class library?

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

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

like image 921
gices Avatar asked Feb 23 '11 16:02

gices


1 Answers

I managed to get this to work based on the resx's designer file. If you open it up and look at the ResourceManager property's get accessor, you can basically just copy the line in order to get access to the same resources.

Full Explanation

First of all, you need to open your resource file's .designer.cs file. It should be in your Solution Explorer as in the following image:

Resource file designer file location in solution explorer

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

In the get accessor, you should see it assign something to a 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 that, I created a ResourceManager in the class I wanted to use in my class library like so:

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

Note 1: Don't forget to add using System.Resources; and using System.Reflection; to the top of the file.
Note 2: This doesn't require adding a reference to the web project to the class library.

Then, I just call the GetString method on my lang variable to get the resources I want.
E.g. lang.GetString("MyErrorMessage").
It's not as elegant as calling Resources.Lang.MyErrorMessage, but it gets the job done.

Hope this helps. Drop a comment below if you have any questions.

like image 56
Richard Marskell - Drackir Avatar answered Oct 03 '22 14:10

Richard Marskell - Drackir