Reputation: 1953
With regard to Web Api, are static classes loaded into memory at every request? If not, what should be used to use the same static class for every request and load it into memory once? I am thinking of loading a class containing a dictionary.
Upvotes: 0
Views: 3004
Reputation: 62228
A static type is initialized only once per application domain and only when referenced. Web API 4.x and previous (not core version) are hosted in IIS which hosts the site in their own application domain 1 domain per site.
If you want a shared readonly dictionary then you could make use of a static type, it will be loaded once and all your loaded instances could reference that same dictionary regardless of what request they were on. I am not advocating this idea as that would be going into the realm of opinion, I am simply stating that this is possible.
Upvotes: 0
Reputation: 772
A static class is loaded once and static members are shared between all instances - if you wish to share a dictionary, then declare it as a static member of a class (the class itself does not need to be static).
One thing that is important to note: if your app is running under IIS and you configure it to allow multiple process instances, then those instances will NOT share static class instances since they are in different processes. This is not the default - if you use default IIS settings, then only one process will service requests and you will be fine - otherwise you will need to have a different approach, for example a secondary shared in-memory cache or service or database that then becomes the shared storage for the dictionary.
Upvotes: 1