Thursday 19 July 2012

ASP.NET MVC 3 Share App_GlobalResources files in all Class Libraries

I wanted to add all my global resource/.resx files e.g. Error Messages into the  the same folder in the ASP.NET MVC 3 App_GlobalResources folder and shared the settings in all referenced class libraries. Well, the idea is to have only one file to maintain, as opposed to ErrorMessage resource file per class library. So I went through the following steps:


  • Write-Click the ASP.NET MVC 3 project and Add ASP.NET Folder App_GlobalResources.
  • Change the Access Modifier to "Public" from "Internal". If this is greyed out in the VS 2010 UI, open the accompanying .Designer.cs file and change the access level to "Public".
Inside the ASP.NET MVC 3 project you can access this resource using the class generated in the Designer.cs file. Life is a little different from inside a references class library, but not too complicated. If you open the .Designer.cs file you will notice the Strongly-Typed references utilises the ResourceManager class in the System.Resources Namespace.

I will use the same class from the class libraries. Find the code below;

var temp = new ResourceManager("Resources.ErrorMessages", Assembly.Load("App_GlobalResources"));
var resourceNameString = temp.GetString("My_Resource_Name");

Of course in a real application it will be advisable to create a custom strongly-typed and Interfaced class 
with properties that will return the values of your settings, so you can unit test your main application code by mocking the settings in your resource files.

Happy coding!!!!.

No comments:

Post a Comment