6

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.

RoastBeast
  • 1,059
  • 2
  • 22
  • 38
Raul Medeiros
  • 177
  • 2
  • 9

1 Answers1

8

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 4
    You missing to add the new service to **ConfigureServices** on **Startup** like this: `services.AddSingleton();` – Max Apr 09 '18 at 15:55
  • @Max Well yes, but since OP is already doing DI, they will know how to do that. – DavidG Apr 09 '18 at 15:57
  • 7
    Of course, but a new user might not know it and would not be able to get your code working – Max Apr 09 '18 at 16:02