简体   繁体   中英

Sharing variables across ASP.NET Core controllers and first initialization

I have a set of variables that should be accessable from the various controllers. Because it's quite a lengthy operation to load them in I would like to only load them in once at the startup of the application and afterwards be able to access them across the various controllers setup.

Right now my best solution was using a static object that intializes and holds all the variables by calling a method "Initialize", but it feels quite hacked in and improper.

What would be a better solution to achieve the same?

You can create instance class, put all your properties in it and register it as a Singleton in DI container. You will receive that instance for each controller in constructor. In Startup.cs ConfigureServices method:

services.AddSingleton<YourPropertiesClass()>;

Another option would be to user InMemoryCache: https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory But for your situation I think that is overcomplication.

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