title: Asp.Net Core async lazy initialization per request
body: <p>For many endpoints in our multi-tenant Asp.Net Core 2.2 web app, we need to get some tenant information from our database on a per-request basis (using an asynchronous database call), then reuse that information from various points in the request pipeline as required without having to make a database call each time. That is, we'd like something like a lazy async property on a per-request basis.</p>
  
  <p>Based on the various docs I've read, instances of <strong>scoped</strong> services are only ever accessed by one thread at a time (the thread processing the request). So, I believe this means that I should be able to safely do something like the following:</p>
  
  <pre><code>// Registered as scoped in the DI container
  public class TenantInfoRetriever : ITenantInfoRetriever
  {
      private TenantInfo _tenantInfo;
      private bool _initialized;
  
      public async Task&lt;TenantInfo&gt; GetAsync()
      {
          // This code is obviously not thread safe, which is why it's important that no two threads are running here at the same time.
          if (!_initialized)
          {
              _tenantInfo = await GetTenantInfoAsync(); // this might actually legitimately return null, hence the need for the separate property "_initialized"
              _initialized = true;
          }
          return _tenantInfo;
      }
  
      private async Task&lt;TenantInfo&gt; GetTenantInfoAsync()
      {
          return await DoDatabaseCallToGetTenantInfo(); // of course this would use an injected EfContext instance (scoped service)
      }
  }
  </code></pre>
  
  <p>To the best of my knowledge this should work because scoped services don't need to be thread-safe. </p>
  
  <p><strong>My question:</strong> are my assumptions here correct, or am I perhaps missing something important?</p>