问题
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:
- Instantiate the class in my application start method.
- Store the instance on the HttpConfiguration.Properties
- Create a
ControllerBase
class which inherits fromApiController
. - Override the
Initialize(HttpControllerContext)
method in myControllerBase
class. This override would read the configuration instance fromHttpControllerContext.Configuration.Properties
and assign it to a property / field inControllerBase
.
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