I've got a simple ASP.NET MVC controller. Inside a few action methods, I access a resource which I'll say is expensive.
So I thought, why not make it static. So instead of doing double checked locking I thought I can leverage the use of Lazy<T> in .NET 4.0. Call the expensive service once instead of multiple times.
So, if this is my pseduo code, how can I change it do use Lazy<T>. For this contrite example, I'll use the File System as the expensive resource So with this example, instead of getting all the files from the destination path, every time a request calls that ActionMethod, I was hoping to use Lazy to hold that list of files .. which of course, makes the call the first time only.
Next assumption: don't worry if the content is changed. That's out of scope, here.
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); } }
Lazyto create a singleton...