【问题标题】:Initialize static class only once and keep it running forever只初始化一次静态类并让它永远运行
【发布时间】:2020-09-08 01:00:18
【问题描述】:

我有一个 Asp.Net Core 3.1 Razor Pages 网站,其中有一个静态的 Repository 类,其中包含最常用的项目。我经常搜索这些项目,初始化它们大约需要 4 分钟。

public static class Repository
{
    public static Dictionary<int, RepositoryPerson> People { get; private set; }
    public static async Task InitAsync(INoSqlSettings settings)
    {
        if (People != null || loading)
        {
            return;
        }

        loading = true;
        var people = await db.People.ToDictionaryAsync(p => p.Id);
        People = ConvertToRepository(people);
        //..and lots of other stuff
        loading = false;
    }
}

起初,我尝试使用托管服务加载它,但由于耗时太长而失败。现在我将它加载到Index.cshtml.cs 文件的OnGetAsync() 中。但问题是每隔一段时间,似乎 .exe 文件会因为网站再次初始化而关闭。这是正常的吗?如何让程序只运行一次并永久共享内存存储库?

【问题讨论】:

标签: asp.net asp.net-core razor-pages


【解决方案1】:

为什么你把这个类声明为静态的?常用的方式as described in the docs是使用ASP.Net Core的依赖注入机制。

您可以通过在 Startup.cs 中将您的类实例注册为 Singleton 来实现它:

public void ConfigureServices(IServiceCollection services)
{

   //...

   var myRepo = new Repository();
   repo.InitAsync(someSettings); //Not async now

   services.AddSingleton<Repository>(myRepo);

   //...

}

然后使用依赖注入检索实例,如下所示:

public class MyPageModel : PageModel
{
    private readonly Repository _repo;

    public MyPageModel(Repository repo)
    {
        _repo = repo;
    }

docs for Razor page dependency injection

【讨论】:

  • 好的,但您认为这是问题所在吗?我真的不认为是这样。因为对我来说,静态类似乎应该在应用程序的生命周期内保存这些值,并且网站可能会以某种方式关闭?那可能吗?使用 Dl 会改变行为吗?
  • @AlirezaNoori 不,改用 DI 并不能解决您当前的问题,但这仍然是个好主意。
猜你喜欢
  • 2017-07-01
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2015-08-23
  • 2020-07-16
  • 2020-04-14
  • 1970-01-01
相关资源
最近更新 更多