Caching application data in memory: MVC Web API

2019-02-02 23:51发布

I am writing an MVC webAPI that will be used to return values that will be bound to dropdown boxes or used as type-ahead textbox results on a website, and I want to cache values in memory so that I do not need to perform database requests every time the API is hit.

I am going to use the MemoryCache class and I know I can populate the cache when the first request comes in but I don't want the first request to the API to be slower than others. My question is: Is there a way for me to automatically populate the cache when the WebAPI first starts? I see there is an "App_Start" folder, maybe I just throw something in here?

After the initial population, I will probably run an hourly/daily request to update the cache as required.

MemoryCache: http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx

UDPATE

Ela's answer below did the trick, basically I just needed to look at the abilities of Global.asax. Thanks for the quick help here, this has spun up a separate question for me about the pros/cons of different caching types.

Pros/Cons of different ASP.NET Caching Options

1条回答
ら.Afraid
2楼-- · 2019-02-03 00:09

You can use the global.asax appplication start method to initialize resources. Resources which will be used application wide basically.

The following link should help you to find more information: http://www.asp.net/web-forms/tutorials/data-access/caching-data/caching-data-at-application-startup-cs

Hint: If you use in process caching (which is usually the case if you cache something within the web context / thread), keep in mind that your web application is controlled by IIS. The standard IIS configuration will shut down your web application after 20 minutes if no user requests have to be served. This means, that any resources you have in memory, will be freed.

After this happens, the next time a user accesses your web application, the global asax, application start will be excecuted again, because IIS reinitializes your web application. If you want to prevent this behaviour, you either configure the application pool idle timeout to not time out after 20minutes. Or you use a different cache strategy (persistent cache, distributed cache...).

To configure IIS for this, here you can find more information: http://brad.kingsleyblog.com/IIS7-Application-Pool-Idle-Time-out-Settings/

查看更多
登录 后发表回答