简体   繁体   English

Web Api和静态类

[英]Web Api And Static Classes

With regard to Web Api, are static classes loaded into memory at every request? 关于Web Api,是否在每次请求时将静态类加载到内存中? 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. 需要注意的一件事:如果您的应用程序在IIS下运行,并且将其配置为允许多个流程实例,则这些实例将不会共享静态类实例,因为它们位于不同的进程中。 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. 这不是默认值-如果您使用默认的IIS设置,则只有一个进程可以处理请求,并且会很好-否则,您将需要采用其他方法,例如,辅助共享内存缓存或服务或数据库然后成为字典的共享存储。

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. Web API 4.x和以前的版本(不是核心版本)托管在IIS中,IIS在每个站点各自的应用程序域1域中托管站点。

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. 我不是在提倡这个想法,因为这将进入观点领域,我只是在说这是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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