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

谁都会走 提交于 2020-05-15 03:56:05

问题


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

@inject IConfigurationService ConfigurationService

And access it each View Page like below:

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

This works, but each page I have to copy and paste the code. I've tried to write the code in _Layout.cshtml but don't works. Static vars also don't works because the values are not static, each request I get the current user configuration and inject in the page. All page that requires the currencySymbol variable value I need to paste code, and I don't want this.

My question is: how can I declare variables in, for example, _Layout.cshtml, or _ViewStart.cshtml or another, thats can be accessed by all razor view pages, like inherits. This variables must contains ConfigurationService values.

Sorry for my english.


回答1:


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.



来源:https://stackoverflow.com/questions/47857068/declare-global-razor-page-variables-in-asp-net-mvc-not-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!