Search code examples
c#asp.net-mvcresx

Initialising custom resources in MVC project


I am creating my own resource files via T4, since they are saved in the database.

The result is for example:

namespace Resources
{
    public class Backoffice {

        internal static IResourceProvider resourceProvider = 
             new JsonResourceProvider(
                 "Backoffice", 
                 (int)System.Web.HttpContext.Current.Session["ApplicationId"]);

        public static string AlgemeenActief 
        {
             get {
                 var resource = 
                     resourceProvider.GetResource(
                         "AlgemeenActief",
                         CultureInfo.CurrentUICulture.Name);

                 if (string.IsNullOrEmpty(resource))
                 {
                     switch ($"{CultureInfo.CurrentUICulture.Name}_{(int) System.Web.HttpContext.Current.Session["ApplicationId"]}")
                     {
                         default:
                         case "nl-NL_6":
                             return "Actief";
                         case "en-GB_6":
                             return "Active";
                     }
                 }
                 return resource;
            }
        }
    }
}

This allows me to use my resources in the same way as the standard .NET resources (I can now type Resources.Backoffice.AlgemeenActief, and I have intellisense showing me the properties).

I get an error because the class is not initialised however. Im not sure how they are initialised in .NET however. I tried to find usages of the constructor in a microsoft resource class:

internal Backoffice() {
}

This does not return any results. Does anyone know how the resource objects are initiated and how I can mimic this?


Solution

  • In this case you could make your class static:

    public static class Backoffice
    

    and call the property getter like this:

    var resource = Backoffice.AlgemeenActief;
    

    Alternatively, leave your class definition as it is and instantiate a BackOffice object like this:

    var backOffice = new BackOffice();
    

    and call the property getter like this:

    var resource = backOffice.AlgemeenActief;