我有一個簡單的ASP.NET MVC
控制器。在一些動作方法中,我訪問一個資源,我會說很貴。如何在ASP.NET MVC控制器中使用懶惰<T>?
所以我想,爲什麼不把它變成靜態的。因此,我認爲我可以利用.NET 4.0中的Lazy<T>
來代替double checked locking。一次而不是多次撥打昂貴的服務。
所以,如果這是我的pseduo代碼,我該如何改變它使用Lazy<T>
。 對於這個痛苦的例子,我將使用File System
作爲昂貴的資源 因此,在這個例子中,不是從目標路徑獲取所有文件,每次請求調用ActionMethod時,我都希望使用Lazy保存文件列表..這當然只是第一次打電話。
下一個假設:如果內容發生變化,請不要擔心。這裏超出了範圍。
public class FooController : Controller
{
private readonly IFoo _foo;
public FooController(IFoo foo)
{
_foo = foo;
}
public ActionResult PewPew()
{
// Grab all the files in a folder.
// nb. _foo.PathToFiles = "/Content/Images/Harro"
var files = Directory.GetFiles(Server.MapPath(_foo.PathToFiles));
// Note: No, I wouldn't return all the files but a concerete view model
// with only the data from a File object, I require.
return View(files);
}
}
使用ASP.NET緩存有什麼問題? – tvanfosson
這聽起來像你正在尋找一個單例,而不是懶惰的對象實例化。當然,你可以*使用懶惰''創建一個單身... –