title: Enable ApplicationInsights based on Configuration
body: <p>I want Azure ApplicationInsights to only be used in an ASP.NET Core application if specified by a Configuration value that is set in <code>appsettings.json</code>.</p>
  
  <p>I put this in my <code>_Layout.cshml</code> to disable client-side insights:</p>
  
  <pre><code>    @if (Configuration.GetSection("UseInsights").Get&lt;bool&gt;())
      {
          @Html.Raw(JavaScriptSnippet.FullScript)
      }
  </code></pre>
  
  <p>But server-side telemetry is still sent, so I added this when its disabled via Configuration:</p>
  
  <pre><code>TelemetryConfiguration.Active.DisableTelemetry = true;
  </code></pre>
  
  <p>This stopped Request and Exception data from being sent, but things like CPU usage were still being sent and visible on my Insights dashboard.</p>
  
  <p>What I think would be the proper method is to enable the <code>.UseApplicationInsights()</code> extension on <code>WebHost.CreateDefaultBuilder()</code> conditionally, but this is a chicken and egg scenario since I don't have access to the Configuration settings until after the Host has been built. Is there somewhere I can fully disable insights after calling <code>BuildWebHost()</code>?</p>