title: URLRewrite middleware that depends on Config dependency injection/scoped service. .Net Core
body: <p>Struggling a little with Dependency Injection/Scoped Services with a rewrite rule class.</p>
  <p>I have a redirects class which implements <code>IRule</code></p>
  <pre><code>class ActivateRedirects : IRule
  {        
      public void ApplyRule(RewriteContext context)
      {
          // Do stuff here which relies on CoreSettings (info below)
      }
  }
  </code></pre>
  <p>I also have a <code>CoreSettings</code> class which contains various settings, some of which are required for <code>ApplyRule</code> to work, it is initialised in <code>startup.cs</code> as follows.</p>
  <pre><code>var configurationBuilder = new ConfigurationBuilder();
  configurationBuilder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), &quot;site.json&quot;), optional: false, reloadOnChange: true);
  IConfigurationRoot root = configurationBuilder.Build();             
  CoreSettings s = new CoreSettings();  
  services.Configure&lt;CoreSettings&gt;(root.GetSection(&quot;Website&quot;));
  </code></pre>
  <p>So you can see above, <code>CoreSettings</code> is created as a Service, which in most cases I can consume with DI:</p>
  <pre><code>public class SomeOtherClass{
      private CoreSettings Settings;
      public SomeOtherClass(Microsoft.Extensions.Options.IOptionsSnapshot&lt;CoreSettings&gt; S)
      {
          Settings = S.Value;
      } 
      // Do stuff with Settings ....
  }
  </code></pre>
  <p>I have read up on several pages on why I can't simply add DI to the <code>ActivateRedirects</code> Class, or explicitly pass the value in using <code>app.ApplicationServices.GetRequiredService</code> but everything I have read is telling what I <em><strong>can't</strong></em> do, I can't find anything to tell me what I <em><strong>can</strong></em>!!</p>
  <p>Before I am told to rewrite the code to not require <code>CoreSettings</code> for Rewriting, I can't do that because one of the rewrite rules depends on a condition which is set by a remote server via a <code>REST API</code> and what is needed in the <code>CoreSettings</code> class is the API credentials used to create the <code>REST Client</code>.</p>