With the way my site is setup, I have a master page, page and then controls within that page, all that can display information about the viewing user.
Because I am requiring this information quite a few times, I am having to create an instance of my model, then returning the User object for each time I need to read data from their account.
As a way to combat this, I done the following:
public static class Core
{
private static PatientRow Patient;
public static PatientRow GetCurrentPatient()
{
if (Patient == null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole("Patient"))
{
using (PatientModel model = new PatientModel())
{
Patient = model.Find<PatientRow>(User.CurrentUser.UserID);
}
}
return Patient;
}
}
As you can see, I’m check to see if the private static variable Patient is null, if so, going away and getting it. The next time I call GetCurrentPatient, as Patient is already populated, I’ve just saved my self a database call etc.
Now comes the issue… As we all know, this will mean every time I call GetCurrentPatient, no matter who is viewing the site, they will get the last (or first) set value.
I don’t want to be storing objects in the Session, it’s naughty, but I do need to find a way to either restrict the static scope to the User’s session, or, a reasonable comprimise, to restrict it to the current page’s execution.
Any suggestions?
Cheers
Edit: Prior to reading Darin’s answer, I had implemented the following.
Every Page I have, inherits a BasePage class (to make things easier for handling menu’s etc). As any code stored in here is only available during the execution (with the exception to static variables), I simply created a Registry Dictionary collection and then from my originating GetCurrentPatient, I simply checked if the registry contained that object, if so, returned it, if not got it, stored it and finally returned it.
I’ll be making changes to my current code to match that of Darin’s. Much appreciated Darin!
You could store it inside the
HttpContext.Current.Itemsbag. It will be available during the entire execution of an HTTP request and obviously restricted only to the current user. So if you call theGetCurrentPatientmethod multiple times from multiple places within the same request it will hit the database only once. If you need to persist this information for more than a request you need to use Session.For example:
Don’t store anything in static fields especially if this information is tied to the current user only.