簡體   English   中英

ASP.NET MVC 4中的全局變量

[英]Global Variables in ASP.NET MVC 4

我目前正在構建一個ASP.Net MVC 4 SAAS應用程序(C#),並停留在設計計划上。 我的意思是,如果客戶選擇Plan A那么他們應該可以訪問某些東西,如果選擇Plan B則可以訪問其他東西,依此類推。

我堅持的部分是與所有操作共享帳戶計划的最佳實踐。 我意識到擁有全局變量是不好的做法,但我確實不想往返於數據庫以獲取每個動作的計划。

我正在想做的事情是這樣的SO答案 ,他們只是聲明一個靜態模型並在某個時候設置它,以后再訪問它。 您認為這是最好的方法嗎? 有沒有更好的辦法?

我認為最佳實踐是您應該在項目中包含IoC並將配置對象注入控制器。

控制器的示例代碼:

public class YourController : Controller
 {
     private IConfigService _configService;

     //inject your configuration object here.
     public YourController(IConfigService configService){
           // A guard clause to ensure we have a config object or there is something wrong
           if (configService == null){
               throw new ArgumentNullException("configService");
           }
           _configService = configService;
     }
 }

您可以將IoC配置為為此配置對象指定單例作用域。 如果需要將此模式應用於所有控制器,則可以創建基本控制器類以重用代碼。

您的IConfigService

public interface IConfigService
{
    string ConfiguredPlan{ get; }
}

您的ConfigService:

public class ConfigService : IConfigService
{
    private string _ConfiguredPlan = null;

    public string ConfiguredPlan
    {
        get
        {
            if (_ConfiguredPlan == null){
                    //load configured plan from DB
            }
            return _ConfiguredPlan;
        }
    }
}
  • 此類很容易擴展,以包括更多配置,例如連接字符串,默認超時,...
  • 我們正在將接口傳遞給控制器​​類,在單元測試期間我們很容易模擬該對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM