如何在构建后自动实例化单例?
我有一个 ASP.NET 2 C# 应用程序,它使用单例从数据库加载大量数据。
对此单例的第一个请求非常慢(如预期)。后续的速度非常快。无论如何,项目构建后就可以实例化单例吗?
I have an ASP.NET 2 C# application that uses a Singleton to load a large list of Data from a Database.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 WebActivator 将其创建为 App_Start 配置类。
假设您的应用程序设置为虚拟目录,App_Start 中的代码将在构建后立即调用。
请注意,这会让您觉得您的构建速度“慢”。另请注意,如果在此代码期间出现异常,您实际上会收到“构建失败”,并带有类似于以下内容的神秘错误消息:
Exception has been returned by the target of an incalling.. ASPRUNTIME ProjectName
This这意味着您需要在浏览器中浏览到您的应用程序才能查看真正的错误消息。
当我们将 EF 迁移绑定到 App_Start 配置中时,我们遇到了所有这些问题。
Create it as an App_Start configuration class with WebActivator.
Assuming your application is setup as a virtual directory the code in App_Start will be called immediately after build.
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.
在构建单例之后,无法在不运行实际应用程序的情况下直接从数据库填充单例。您可以通过将单例填充在与应用程序其余部分不同的单独线程上(在
Application_Start
中)来加速它,但是,如果在完全使用单例之前使用单例,则这不会解决速度下降的问题已加载(并且还需要添加锁定逻辑)。将大量数据从数据库加载到单例中是否有特定原因?
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).Is there a specific reason why you're loading a large amount of data from the database into the singleton?
您可以将用于填充单例的代码放入 global.asax.cs 的
Application_Start
方法中。来自 MSDN:
You could put the code to populate the singleton in the
Application_Start
method in global.asax.cs.From MSDN: