views:

33

answers:

1

Fairly simple issue which is solved in PHP by using a static variable.

private static $pages;
public function Pages() {
    if($pages == null) {
        $pages = new PageCollection();
        $pages->findAll();
    }
}

Everywhere in my code I use Pages()::someFindFunction() to make sure the results are fetched only once, and I use that same collection.

I want the same in my .NET MVC application: use something like:

<%=MySite.Pages.findById(1).Title%>

In the code below, if I use a private variable, or if I use a public class with shared variables (doesn't matter) they are both persisted during the entire application.

I want them to load the same way PHP does, once per request. Now where do I store the .NET equivalent of private static $pages, so that the code below works?

            //what to do with $pages??

Public Module MySite
    Public Function Pages() As PageCollection
        If $pages Is Nothing Then
            $pages.loadAll()
        End If
        Return $pages
    End Function
End Module
+1  A: 

1st, are you sure you want a module? Normally, you'd use a class.

Public Class MySiteController
    Private _pages as PageCollection
    ReadOnly Property Pages As PageCollection 
        Get
          If _pages Is Nothing Then 
            _pages = New PageCollection
            _pages.FindAll
          End If 
          Return _pages 
        End Get 
    End Function 

    ... other code here...

    '' use it as:  Pages.FindById(1)
End Class
Cheeso
Fine, but where does the class live? It needs to be instantiated doesn't it?
Ropstah
Ah, I see. If you are doing MVC, the class can be your controller.
Cheeso
But what happens if you start mixing up controller requests?
Ropstah
It's my understanding that a controller is instantiated for each request. So if you have multiple concurrent requests, they get different instances, and different PageCollections. If you want the PageCollection to be scoped to a session, so that multiple concurrent requests from the same browser would use the same PageCollection, and use it across multiple requests, then you should stuff the PageCollection into Session State.
Cheeso
I'm confused. I really don't mean 'sharing between requests'. But just use a globally referenced variable everywhere in code. I understand this is very bad design, but why is this so hard to do? Isn't is just possible to create a request-scoped static variable?
Ropstah
Actually I did need an application wide reference, however a wrong call somewhere made something messed up... I had two caches running: AllPages() and AllPages(cultureCode). See where I'm going? I was editing the AllPages() reference while using AllPages(cultureCode) everywhere on the site :)
Ropstah