1

I am migrating a legacy application written in Asp.Net MVC framework to ASP.net core MVC and some classes use HttpApplicationState to share cache object between all the users of the app

I've tried to read online about a replacement for this object (like IFormFile replacing HttpPostedFile) but could not find any information regarding this object

/* This method being called from the global.asax file in framework app and 
   usses the HttpApplicationState  */
public static void Foo(HttpApplicationState app)
{
   app.Set("Cache", cache);
}

I would like to know how can i achieve a similar behavior in my migrated application

2 Answers2

1

The answer to this question is very simple.

First, know that the HttpApplicationState object stores data for all users and sessions to use, quote "Unlike session state, which is specific to a single user session, application state applies to all users and sessions.".

Therefore, you can look at the HttpApplicationState object as a basic caching object that is shared across all.

So to answer your question, the replacement for the HttpApplicationState object is:

  • IMemoryCache which could be the literal replacement of HttpApplicationState if you want to replicate (more or less) the legacy application
  • IDistributedCache which is much more recommended nowadays
Ray
  • 7,940
  • 7
  • 58
  • 90
taz mazia
  • 182
  • 10
0

You can add a singleton in the DI container:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ClassToStoreData>();
}

After this you can access the data by adding this parameter to the constructor of any class:

public class SomeClassThatUsesCache
{
    public SomeClassThatUsesCache(ClassToStoreData cache)
    {

    }
}

The data inside ClassToStoreData will be available to all users and any place in your application

Ray
  • 7,940
  • 7
  • 58
  • 90
  • The problem with this solution is that i would need to convert all of the classes in the app to instantiated through the DI and i was hoping to avoid this kind of massive refactor (yes its an old app, 2010 old) – Kawhi James Aug 22 '19 at 13:49
  • You can use a static class that has a reference to the ClassToStoreData which is set in the Configure method of your startup but I would not recommend it. – Dinand Lybaert Aug 22 '19 at 13:59