简体   繁体   English

构建后如何自动实例化单例?

[英]How do I automatically instantiate a singleton after a build?

I have an ASP.NET 2 C# application that uses a Singleton to load a large list of Data from a Database. 我有一个使用Singleton从数据库加载大量数据的ASP.NET 2 C#应用程序。

The first request for this singleton very slow (as expected). 此单例的第一个请求非常慢(如预期)。 The subsequent ones are very fast. 随后的速度非常快。 Is there anyway to instantiate the singleton as soon as the project is built? 无论如何,一旦项目建立,就可以实例化单例吗?

There is no way of populating a singleton from the database directly after it has been built without running the actual application. 无法在不运行实际应用程序的情况下直接在数据库中填充单例。 You could potentially speed it up by having the singleton be populated on a seperate thread from the rest of the application (in Application_Start ) this however will not solve the slowdown issue if the singleton is used before it is fully loaded (and also requires the addition of locking logic). 您可以通过将单例填充到与应用程序其余部分(在Application_Start )中的单独线程中来加快它的速度,但是,如果在完全加载单例之前使用单例,这将无法解决速度下降的问题(并且还需要添加逻辑)。

Is there a specific reason why you're loading a large amount of data from the database into the singleton? 为什么要从数据库将大量数据加载到单例中,是否有特定原因?

You could put the code to populate the singleton in the Application_Start method in global.asax.cs. 可以在Global.asax.cs的Application_Start方法中放入用于填充单例的代码。

From MSDN : MSDN

Called when the first resource (such as a page) in an ASP.NET application is requested. 当请求ASP.NET应用程序中的第一个资源(例如页面)时调用。 The Application_Start method is called only one time during the life cycle of an application. 在应用程序的生命周期中,仅一次调用Application_Start方法。 You can use this method to perform startup tasks such as loading data into the cache and initializing static values. 您可以使用此方法执行启动任务,例如将数据加载到缓存中并初始化静态值。

Create it as an App_Start configuration class with WebActivator . 创建它作为与App_Start配置类WebActivator

Assuming your application is setup as a virtual directory the code in App_Start will be called immediately after build. 假设您的应用程序设置为虚拟目录,则App_Start中的代码将在构建后立即调用。

Note, this will give you the appearance that your builds are "slow". 请注意,这会使您的构建看上去“缓慢”。 Also note, if you get an exception during this code you will actually get a "build failure" with an arcane error message similar to: 另请注意,如果在这段代码中遇到异常,则实际上会出现“构建失败”,并显示类似于以下内容的神秘错误消息:

Exception has been thrown by the target of an invocation.. ASPRUNTIME ProjectName

This is means you need to browse to your app in a browser to see the real error message. 这意味着您需要在浏览器中浏览到您的应用程序才能看到真正的错误消息。

We encountered all of this when we tied in EF Migrations into a App_Start configuration. 将EF迁移绑定到App_Start配置中时,我们遇到了所有这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM