title: What is the best way to share a Configuration object used in ASP.NET Core 3.1 Startup and Controllers
body: <p>What is the best way to share a configuration object between the ASP.NET Core 3.1 Startup class and Controllers?</p>
  
  <p>I have seen some examples using DI, and this seems like a good idea, but I need to use the dependency within <code>public void ConfigureServices(IServiceCollection services)</code>.</p>
  
  <p>Furthermore the object depends on a <code>Microsoft.Extensions.Configuration.IConfiguration</code> instance.</p>
  
  <blockquote>
    <p>The object will be used within <code>Startup.cs</code>, within the <code>ConfigureServices</code> itself as well as in <code>Controllers</code>.</p>
  </blockquote>
  
  <p>Would DI work? Or is the solution a Singleton with parameters?</p>
  
  <p>Here is the specific code that needs to be shared:</p>
  
  <pre><code>// openssl rand -hex 16 =&gt; 256 bits when read
  var jwt_key = Configuration.GetSection("JwtOption:IssuerSigningKey").Value;
  var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwt_key));
  
  var tokenValidationParameters = new TokenValidationParameters
  {
      // The signing key must match!
      ValidateIssuerSigningKey = true,
      IssuerSigningKey = signingKey,
  
      // Validate the JWT Issuer (iss) claim
      ValidateIssuer = true,
      ValidIssuer = "some host name",
  
      // Validate the JWT Audience (aud) claim
      ValidateAudience = true,
      ValidAudience = "web_intranet",
  
      // Validate the token expiry
      ValidateLifetime = true,
  
      // If you want to allow a certain amount of clock drift, set that here:
      ClockSkew = TimeSpan.Zero
  };
  </code></pre>
  
  <p>This object is used as follows within the <code>public void ConfigureServices(IServiceCollection services)</code> method</p>
  
  <pre><code>services
      .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options =&gt;
      {                
          options.TicketDataFormat = new CustomJwtDataFormat(
              SecurityAlgorithms.HmacSha256,
              tokenValidationParameters);
      });
  </code></pre>