title: How to correctly get dependent scoped services from ISecurityTokenValidator
body: <p>In my asp.net core 2.0 web app, I've got a custom <code>ISecurityTokenValidator</code> which validates tokens.</p>
  
  <p>It depends on a repository to do a db lookup - the repository itself is setup as a scoped dependency:</p>
  
  <pre><code>services.AddScoped&lt;IMyRepository&gt;(MyRepository);
  </code></pre>
  
  <p>Now the funkiness comes about because of the way the ISecurityTokenValidator is setup.</p>
  
  <p>It's added in <code>ConfigureServices</code>:</p>
  
  <pre><code>.AddJwtBearer(options =&gt;
      {
          options.SecurityTokenValidators.Clear();
          options.SecurityTokenValidators.Add(new MyTokenValidator(services.BuildServiceProvider()));
      })
  </code></pre>
  
  <p>This is how it looks:</p>
  
  <pre><code>public class MyTokenValidator : ISecurityTokenValidator
  {
      private readonly IServiceProvider _serviceProvider;
  
      public MyTokenValidator(IServiceProvider serviceProvider)
      {
          _serviceProvider = serviceProvider;
      }
  
      public bool CanReadToken(string securityToken) =&gt; true;
  
      public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters,
          out SecurityToken validatedToken)
      {
  
          var serviceScopeFactory = _serviceProvider.GetRequiredService&lt;IServiceScopeFactory&gt;();
  
          using (var scope = serviceScopeFactory.CreateScope())
          {
              var myRepository = scope.ServiceProvider.GetService&lt;IMyRepository&gt;();
              var principalFactory = scope.ServiceProvider.GetService&lt;IUserClaimsPrincipalFactory&lt;User&gt;&gt;();
  
              // Use the repo....
  
          }
  
      }
  }
  </code></pre>
  
  <p>Now, because the <code>IsecurityTokenProvider</code> is only instantiated once, it's effectively a singleton. When I use the service provider to ask for a <code>IMyRepository</code> I was finding that I was always received the same object - there is no new scope as far as it was concerned, because it's in a singleton class.</p>
  
  <p>To get round that, you'll see in the code above Ive had to manually force a new scope every time the token validator is called. Is this really the only way to resolve this, it seems like I'm hacking around to make it work here...</p>