title: How to initialize a scoped injected class in ASP.NET Core involving asynchronous calls
body: <p>I need to initialize an injected class at the scope level in ASP.NET Core - the initialization involves asynchronous method calls.  You wouldn't do this in the constructor, nor a property accessor.</p>
  
  <p>A common DI use in an asp.net core application is getting the current user. I implemented this by creating an <code>IUserContext</code> abstraction and injecting it at the scoped level:</p>
  
  <pre><code>public sealed class AspNetUserContext : IUserContext
  {
      private readonly UserManager&lt;User&gt; userManager;
      private readonly IHttpContextAccessor accessor;
      private User currentUser;
  
      public AspNetUserContext(IHttpContextAccessor a, UserManager&lt;User&gt; userManager) {
          accessor = a;
  
          if (userManager == null)
              throw new ArgumentNullException("userManager");
  
          this.userManager = userManager;
      }
  
      public string Name =&gt; accessor.HttpContext.User?.Identity?.Name;
      public int Id =&gt; accessor.CurrentUserId();
  
      public User CurrentUser {
          get {
              if (currentUser == null) {
                  currentUser = this.UserManager.FindByIdAsync(Id.ToString()).ConfigureAwait(false).GetAwaiter().GetResult();
              }
  
              return currentUser;
          }
      }
  }
  </code></pre>
  
  <p>I am struggling trying to find out how to correctly initialize the <code>CurrentUser</code> property.</p>
  
  <p>Since there is no longer any way to get a user from the <code>UserManager</code> class sychronously, I am not comfortable running an async method from within a property getter when initializing the <code>CurrentUser</code>, nor from the constructor (there are no long any synchronous methods on the <code>UserManager</code> class with ASP.NET Core).</p>
  
  <p>I feel like the correct way to do this would be to run an initialization method on the injected instance somehow once per request since it is scoped (perhaps with an action filter/middleware/Controller base class (or perhaps in the dependency injection <code>AddScoped</code> method itself as a factory method?)</p>
  
  <p>This seems like a pretty common problem and I'm wondering how others have resolved this.</p>