[英]How do I auto instantiate an object (singleton) in ASP.NET Web API v2?
I'm loading a large object in memory into a singleton for reuse between GET requests.我正在将内存中的一个大对象加载到一个单例中,以便在 GET 请求之间重用。 However when the application starts I want the singleton to initialize automatically, currently I have something like this
但是,当应用程序启动时,我希望单例自动初始化,目前我有这样的事情
public HttpResponseMessage GetData([FromBody]string text)
{
var spc = MySingleton.Instance; //runs some long instantiation process on the first call
…
}
So I have to wait until a request comes in before the singleton gets initialized.所以我必须等到请求进来后,才初始化单例。 Is there a way to make the singleton object initialize on its own when I start the application?
当我启动应用程序时,有没有办法让单例对象自行初始化?
I tried putting this line我试着把这条线
var spc = MySingleton.Instance;
In the Application_Start() method of global.asax.cs but it didn't do anything.在 global.asax.cs 的 Application_Start() 方法中,但它没有做任何事情。
Trying use Dependency Injection, hopefully the IOC container will create your configured instance of the singleton object before your first request.尝试使用依赖注入,希望 IOC 容器会在您的第一个请求之前创建您配置的单例对象实例。
In Startup.cs
, in the ConfigureServices
method you will add something like:在
Startup.cs
的ConfigureServices
方法中,您将添加如下内容:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISingleton, Singleton>();
}
From this Singleton pattern tutorial here .来自这里的单例模式教程。
In your controller that has the method GetData
you will change the default constructor from parameter-less to having the Singleton object be a required argument to instantiate that controller.在具有
GetData
方法的控制器中,您将默认构造函数GetData
参数更改为让 Singleton 对象成为实例化该控制器的必需参数。 The .NET Core IOC container will take care of instantiating the controller passing your singleton instance configured in in Startup.ConfigureServices
. .NET Core IOC 容器将负责实例化控制器,传递在
Startup.ConfigureServices
配置的单例实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.