Rion Williams
Rion Williams

Reputation: 76547

Using Cache Storage in MVC2

I have a class that holds valid licenses for a user and every 15 minutes it is "validated" to ensure the current licenses are valid and add/remove any that may have changed.

Currently, this is accessed in my ApplicationController, which every other controller in the application inherits from, so that whenever the user performs any operations, it ensures they have the valid licenses / permissions to do so.

Licensing Model:

public class LicenseModel
{
    public DateTime LastValidated { get; set; }
    public List<License> ValidLicenses { get; set; }
    public bool NeedsValidation
    {
        get{ return ((DateTime.Now - this.LastValidated).Minutes >= 15);}
    }

    //Constructor etc...
}

Validation Process: (occurs inside the Initialize() method of the ApplicationController)

LicenseModel licenseInformation = new LicenseModel();     
if (Session["License"] != null)
{
    licenseInformation = Session["License"] as LicenseModel;
    if (licenseInformation.NeedsValidation)
        licenseInformation.ValidLicenses = Service.GetLicenses();
        licenseInformation.LastValidated = DateTime.Now;
        Session["License"] = licenseInformation;
}
else
{
    licenseInformation = new LicenseModel(Service.GetLicenses());
    Session["License"] = licenseInformation;
}

Summary:

As you can see, this process currently uses the Session to store the LicenseModel, however I was wondering if it might be easier / more-efficient to use the Cache to store this. (Or possibly the OutputCache?) and how I might go about implementing it.

Upvotes: 2

Views: 194

Answers (1)

Bobby Richard
Bobby Richard

Reputation: 648

The cache would definitely make more sense if the licenses are used application wide and are not specific to any user session. The cache can handle the 15 minute expiration for you and you will no longer need the the NeedsValidation or LastValidated properties on your LicenseModel class. You could probably do away with the model all together and just store the List of valid licenses like so:

if (HttpContext.Cache["License"] == null)
{
    HttpContext.Cache.Insert("License",Service.GetLicenses(), null,
    DateTime.Now.AddMinutes(15), Cache.NoSlidingExpiration);
}

var licenses = HttpContext.Cache["License"] as List<License>;

Upvotes: 1

Related Questions