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

Let's say I have a class called MySiteConfigurationin which I have a bunch of, you guessed it, configuration data. This data will not change during the runtime of the application after it is downloaded.

My goal is to create an instance of this class at startup and access it from my actions with the controller. I do not want to create a class more than once, since this is not necessary.

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

  • Create an instance of the class in my application launch method.
  • Store the instance in HttpConfiguration.Properties
  • Create a class ControllerBasethat inherits from ApiController.
  • Override the method Initialize(HttpControllerContext)in my class ControllerBase. This override will read the configuration instance from HttpControllerContext.Configuration.Propertiesand assign it to the property / field in ControllerBase.

Any controller that needs access to a configuration instance inherits ControllerBaseand refers to the underlying property. Not so bad...

With that said, this model does not work in the new structure from what I can say. There is no initialization method to override the new ControllerMVC 6 class . I am also not familiar with the new Startup.cs templates and middleware to know where to start this problem.

Thank.

+4
source share
2 answers

. , .

. .

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

Startup.cs :

services.AddSingleton<MyConfigService>();

( , AddSingleton.)

:

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

?

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

.

public ActionResult Index()
{
    var config = HttpContext.Application["MySiteConfiguration"] as MySiteConfiguration;
}
-1

Source: https://habr.com/ru/post/1569513/


All Articles