簡體   English   中英

將變量從控制器傳遞到單例類並在任何地方訪問此變量

[英]Passing variable from controller to singleton class and access this variable anywhere

我試圖利用單例類來存儲登錄名的用戶名變量。

我從LoginController中的Request.QueryString["username"]獲取用戶Request.QueryString["username"]

我將以下類作為單例:我的問題是如何在單例類中傳遞此Request.QueryString["username"]並在應用程序中的任何位置訪問此變量? 我想在每個控制器中訪問此變量。 請幫忙。

public sealed class Settings
{
    private static Settings instance = null;
    static readonly object padlock = new object();

// initialize your variables here. You can read from database for example
Settings()
{
    this.UserName= "prop1"; // I want to push the variable here
}

public static Settings Instance
{
    get
    {
        lock (padlock)
        {
            if (instance == null)
            {
                instance = new Settings();
            }
            return instance;
        }
    }
}

// declare your global variables here
public string UserName{ get; set; }

}

假設您想擁有一個基於用戶的上下文(由Session本身內部完成)

創建一個Dictionary對象作為Dictionary>來存儲狀態。 外層詞典將保存用戶名,而內層詞典將保存上下文。

下面的偽代碼

// 1.此字典僅需要在靜態構造函數中初始化。

static ctor() {
   stateObject = new Dictionary<string, Dictionary<string, object>()
}

// 2.有一個Login / Logout方法,每個方法都以userName作為參數。

Login(userName) {
   if (stateObject.Keys[userName])   throw new Exception('user already logged in');
   else  stateObject.insert(userName, new Dictionary....)
}

Logout(userName) {
  if (stateObject.Keys[userName])
      stateObject.Remove(userName)
}

// 3.根據需要公開成員以獲取狀態

State(userName, propertyKey) {
     if (stateObject.Keys[userName])
         if (stateObject.Keys[userName].Keys[propertyKey])
             return (stateObject.Keys[userName].Keys[propertyKey])
    else  .. handle exceptions
}

您需要在此處再次傳遞userName的原因是您正在使用Singleton,因此所有實例都將具有其訪問權限。 會話隱式傳遞sessionId,但行為方式完全相同

暫無
暫無

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

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