简体   繁体   中英

Web Api And Static Classes

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM