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

删除回忆录丶 提交于 2020-01-02 05:34:11

问题


Let's say I have a class called MySiteConfiguration in which I have a bunch of, you guessed it, configuration data. This data will not change over the course of the application's runtime after it has been loaded.

My goal would be to construct an instance of this class at startup and access it from my controller actions. I do not want to construct the class more than once, as this should not be needed.

To do this in WebApi 2 for instance, I would:

  1. Instantiate the class in my application start method.
  2. Store the instance on the HttpConfiguration.Properties
  3. Create a ControllerBase class which inherits from ApiController.
  4. Override the Initialize(HttpControllerContext) method in my ControllerBase class. This override would read the configuration instance from HttpControllerContext.Configuration.Properties and assign it to a property / field in ControllerBase.

Any controller needing access to the configuration instance would inherit ControllerBase and reference the base property. Not so bad...

With that said, this pattern does not work in the new framework from what I can tell. There is no initialize method to override on MVC 6's new Controller class. I'm also not familiar enough with the new Startup.cs patterns and middleware available to know where to start with this problem.

Thanks.


回答1:


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.
    }
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/27716923/how-do-you-initialize-application-state-at-startup-and-access-it-from-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!