2015-11-25 321 views
0

我嘗試設置在類的類型IProcessHostPreloadClient Application對象(代碼在應用程序初始化運行時,這裏解釋:http://www.codeproject.com/Articles/795265/IIS-Asp-net-warm-up-Auto-Start-Application):如何設置應用程序啓動應用程序變量

public class DeserializeEdocsProvider : System.Web.Hosting.IProcessHostPreloadClient 
{ 
    public void Preload(string[] parameters) 
    { 
     ... 
      //the following fails with message: 
      //"Object reference not set to an instance of an object." 
      HttpContext.Current.Application["testtest"] = "test"; 
     ... 
    } 
} 

我要的是在應用程序啓動時(在應用程序池的回收之後)創建對象,以及稍後在Web應用程序的其他請求中訪問該對象。任何解決方案是讚賞。

+1

在'Global.asax'中有一個靜態變量,比如'MyVar',在MyClass裏面,並且在'Application_Start()'方法中設置值。稍後,使用'MyClass.MyVar'訪問變量。 – mshsayem

+0

謝謝@mshsayem。你的解決方案幫了我很多! – Batar

回答

0

有一個靜態變量/屬性,說MyVar,你的類裏面,說MyClass

public class MyClass 
{ 
    ... 
    private static int _myVariable; 
    public static int MyVar {get; set;} 
    ... 
} 

現在,Global.asax設置Application_Start()方法中的值(如果Global.asax是不是有添加一個):

protected void Application_Start(object sender, EventArgs e) 
{ 
    ... 
    MyClass.MyVar = 100; 
    ... 
} 

後來,從任何地方訪問變量(它是一個公共靜態屬性):

... 
lblMyLabel.Text = MyClass.MyVar.ToString(); 
... 
相關問題