I have had several occasions recently to access a specific class several times over a relatively small time frame.
So I’ve been storing the value of the class in Session and trying to access it on page load, if it’s not available creating a new instance and storing that in session.
So instead of constantly replicating the same code for different classes on different pages I’m trying to create an extension method to do this for me.
I want to use it like this
Dim objName as MyClass
objName.SessionSingleton()
So far this is what I have for my extension method:
<Extension()> _
Public Sub SessionSingleton(ByRef ClassObject As Object)
Dim objType As Type = ClassObject.GetType
Dim sessionName As String = objType.FullName
If TypeOf HttpContext.Current.Session(sessionName) Is objType And HttpContext.Current.Session(sessionName) <> "" Then
ClassObject = HttpContext.Current.Session(sessionName)
Else
Dim singleton As Object = New objType???????
HttpContext.Current.Session(sessionName) = singleton
ClassObject = singleton
End If
End Sub
I’m stuck on what to do when I make my new instance of my class (it would have to have a New() sub)
I’m not sure where to go from here… or even if this is the best way to do it.
I figured it out and am posting my code for reference. While digging thru pages about Class/Object Factories (thanks RBarry) I found several references to
Activator.CreateInstance()in the System.Reflection Class I came up with this.This will let you create a session based singleton from any class that does not require parameters in the new method (which isn’t required for this to work)
To test I made a simple Class:
You’ll notice the two Public Shared Methods type() and SessionSinglton which calls the above extension method.
With those two functions added we have three ways to initiate the Session Singlton demonstrated here:
The Trace Output for this file is as follows:
The classes new() method is accessed on the first call to the SessionSinglton method and subsequent calls reflect that the instance is in fact being pulled from memory.
I hope this helps someone else in the future.