title: Blazor (Server) scoped object in dependency injection creating multiple instances
body: <p>For demonstration purposes let's say I have a class called StateManager:</p>
  <pre><code>public class StateManager
  {
      public StateManager()
      {
          IsRunning = false;
      }
  
      public void Initialize()
      {
          Id = Guid.NewGuid().ToString();
          IsRunning = true;
          KeepSession();
      }
  
      public void Dispose()
      {
          Id = null;
          IsRunning = false;
      }
  
      public string Id { get; private set; }
      public bool IsRunning { get; private set; }
  
      private async void KeepSession()
      {
          while(IsRunning)
          {
              Console.WriteLine($&quot;{Id} checking in...&quot;);
              await Task.Delay(5000); 
          }
      }
  }
  </code></pre>
  <p>It has a method that runs after it is initiated that writes it's Id to the console every 5 seconds.</p>
  <p>In my Startup class I add it as a Scoped service:</p>
  <pre><code>services.AddScoped&lt;StateManager&gt;();
  </code></pre>
  <p>Maybe I am using the wrong location but in my <strong>MainLayout.razor</strong> file I am initializing it on <strong>OnInitializedAsync()</strong></p>
  <pre><code>@inject Models.StateManager StateManager
  ...
  @code{
      protected override async Task OnInitializedAsync()
      {
          StateManager.Initialize();
      }
  }
  </code></pre>
  <p>When running the application after it renders the first page the console output is showing that there are 2 instances running:</p>
  <blockquote>
  <p>bcf76a96-e343-4186-bda8-f7622f18fb27 checking in...</p>
  <p>e5c9824b-8c93-45e7-a5c3-6498b19ed647 checking in...</p>
  </blockquote>
  <p>If I run <strong>Dispose()</strong> on the object it ends the <strong>KeepSession()</strong> while loop on one of the instances but the other keeps running. If I run <strong>Initialize()</strong> a new instance appears and every time I run <strong>Initialize()</strong> new instances are generated and they are all writing to the console with their unique id's. I am able to create as many as I want without limit.</p>
  <p>I thought injecting a Scoped&lt;&gt; service into the DI guaranteed a single instance of that object per circuit? I also tried initializing within the <strong>OnAfterRender()</strong> override in case the pre-rendering process was creating dual instances (although this does not explain why I can create so many within a page that has the service injected).</p>
  <p>Is there something I am not handling properly? Is there a better location to initialize the StateManager aside from MainLayout?</p>