0

I have an Asp.Net Core 3.1 Razor Pages website in which I have a static Repository class holding the most used items. I search these items a lot and it takes around 4 minutes to initialize them.

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;
    }
}

At first, I tried to load this with a hosted service but it fails because it takes too long. Now I load it in the Index.cshtml.cs file's OnGetAsync(). But the problem is that every once in awhile, it seems like the .exe file closes because the website initializes again. Is this normal? How can I make the program run only once and share the in-memory repository forever?

Alireza Noori
  • 14,961
  • 30
  • 95
  • 179
  • Yes, web applications hosted in IIS commonly recycle. See [Why do IIS application pools need to be recycled?](https://stackoverflow.com/questions/7171367) – mason May 21 '20 at 14:57

1 Answers1

1

Why have you declared the class as static? The common way, as described in the docs, is to use Dependency Injection mechanism of ASP.Net Core.

You can implement it by registering your instance of your class as a Singleton in your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{

   //...

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

   services.AddSingleton<Repository>(myRepo);

   //...

}

Afterwards retrieve the Instance with Dependency Injection, like this:

public class MyPageModel : PageModel
{
    private readonly Repository _repo;

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

See docs for Razor page dependency injection.

StephanB
  • 315
  • 2
  • 17
  • OK sure but do you think that's the problem? I really don't think that's the case. Because to me it seems like the static class should hold the values during the lifetime of the application and maybe the website somehow closes? Is that possible? Does using Dl change the behaviour? – Alireza Noori May 21 '20 at 14:33
  • @AlirezaNoori No, changing to use DI won't fix your current issue, but it's still a good idea. – mason May 21 '20 at 14:59