Search code examples
c#razorasp.net-coreasp.net-core-mvc

Declare global Razor Page variables in ASP.NET MVC [NOT Static]


I have a ConfigurationService class that is injected in "_ViewImports":

@inject IConfigurationService ConfigurationService

And I access it in each View Page like below:

@{
    // Configurations
    var configuration = await ConfigurationService.GetGeneralConfiguration();
    var currencySymbol = configuration.Currency.Symbol;
}

This works, but I have to copy and paste the code in each page. I've tried to write the code in _Layout.cshtml but it doesn't work. Static vars also don't work because the values are not static - for each request I get the current user configuration and inject into the page. And, for all pages that require the currencySymbol variable value I need to paste code, and I don't want to have to do this.

My question is: How can I declare variables in, for example, _Layout.cshtml, or _ViewStart.cshtml or some other view that can be accessed by all razor view pages, like inherits. These variables must contain ConfigurationService values.


Solution

  • Instead of creating variables, you're better off injecting a service that will generate the values you need as required. For example:

    public interface ILocalisationService
    {
        string CurrencySymbol { get; }
    }
    
    public class LocalisationService : ILocalisationService
    {
        private IConfigurationService _configurationService;
        private string _currencySymbol;
    
        public LocalisationService(IConfigurationService configurationService)
        {
            _configurationService = configurationService;
        }
    
        public string CurrencySymbol => string.IsNullOrEmpty(_currencySymbol)
            ? _currencySymbol = _configurationService.GetValue("£")
            : _currencySymbol;
    }
    

    Now inject the new service:

    @inject ILocalisationService LocalisationService
    

    And use it in your view:

    The currency symbol is @LocalisationService.CurrencySymbol
    

    The benefit of this is that when your view doesn't use one of the values, it doesn't need to get calculated, which is especially relevant if it takes a long time.