[英]How to share objects to classes in same request with C# MVC3
我有一個C#MVC3站點。 但是,我需要在同一個請求中將對象共享給多個類。
其他請求無法訪問/不知道共享對象存在。
請求結束后,應刪除共享對象。
此示例代碼可以是每個請求的對象,而不是僅在一個請求中共享對象。
Class ShareObjects
{
private static SomeThing _Data = null;
public static SomeThing Data
{
get
{
if (_Data == null)
{
_Data = new SomeThing();
}
return _Data;
}
}
}
Class ObjectA
{
public ObjectA()
{
var data = ShareObjects.Data;
//Do stuff
}
}
Class ObjectB
{
public ObjectB()
{
var data = ShareObjects.Data;
//Do stuff
}
}
您可以將您的代碼添加到global.asax.cs:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var customContext = CustomHttpContext.Initialize(new HttpContextWrapper( Context) );
}
我們所做的是將它掛鈎到HttpContext上,如上面的代碼所示。 CustomHttpContext Initialize例程如下所示:
public static CustomHttpContext Initialize(HttpContextBase httpContextBase)
{
Guard.IsNotNull(httpContextBase, "httpContext");
// initialize only once
if (! httpContextBase.Items.Contains(key))
{
CustomHttpContext newCustomHttpContext = new CustomHttpContext();
httpContextBase.Items[key] = newCustomHttpContext;
return newCustomHttpContext;
}
return Get(httpContextBase);
}
完成后。 您可以通過提供上下文來調用CustomHttpContext:
CustomHttpContext.Get(HttpContext).PropA;
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.