How do you initialize application state at startup and access it from controllers in MVC 6?

心不动则不痛 提交于 2019-12-05 15:00:17

Use dependency injection. Register a singleton service that has your data, and then use constructor injection on your controllers to acquire the service instance.

First, define a service. A service can really be any class or interface.

public class MyConfigService {
    // declare some properties/methods/whatever on here
}

In your Startup.cs do something like this:

services.AddSingleton<MyConfigService>();

(Note that there are other overloads of AddSingleton depending on your scenario.)

And then consume it in each controller:

public MyController : Controller {
    public MyController(MyConfigService myService) {
        // do something with the service (read some data from it, store it in a private field/property, etc.
    }
}

How about using the application state to store your configuration data?

protected void Application_Start()
{
    Application["MySiteConfiguration"] = new MySiteConfiguration();
}

You can then access your configuration data from inside your controllers.

public ActionResult Index()
{
    var config = HttpContext.Application["MySiteConfiguration"] as MySiteConfiguration;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!