title: How to access a service in ASP.NET Core before building the WebHost?
body: <p>Let's assume that we have the following <code>Program.cs</code>:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static class Program
  {
      public static async Task Main(string[] args)
      {
          await CreateWebHostBuilder(args).Build().RunAsync();
      }
  
      public static IWebHostBuilder CreateWebHostBuilder(string[] args)
      {
          return WebHost
              .CreateDefaultBuilder(args)
              .ConfigureKestrel(options =&gt; { options.AllowSynchronousIO = false; })
              .ConfigureFanciness()
              .ConfigureLogging(ConfigureApplicationLogging)
              .UseStartup&lt;Startup&gt;();
      }
  
      private static void ConfigureApplicationLogging(WebHostBuilderContext context, ILoggingBuilder loggingBuilder)
      {
          var loggingConfiguration = context.Configuration.GetSection("Logging");
  
          loggingBuilder.AddConfiguration(loggingConfiguration);
  
          // var fancyService = SomehowGet&lt;IFancyService&gt;();
          // if (fancyService.IsEnabled)
          //     loggingBuilder.AddEventLog(loggingConfiguration);
      }
  
      public static IWebHostBuilder ConfigureFanciness(this IWebHostBuilder hostBuilder)
      {
          return hostBuilder.ConfigureServices(delegate (WebHostBuilderContext context, IServiceCollection services)
          {
              var fancinessConfiguration = context.Configuration.GetSection("Fanciness");
              services.Configure&lt;FancinessSettings&gt;(fancinessConfiguration);
              services.AddSingleton&lt;IFancyService, FancyService&gt;();
  
              // var fancyService = SomehowGet&lt;IFancyService&gt;();
              // fancyService.Initialize();
          });
      }
  }
  </code></pre>
  
  <p>And the following <code>FancyService.cs</code>:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public sealed class FancyService : IFancyService
  {
      private readonly ILogger&lt;FancyService&gt; logger;
      private readonly IOptions&lt;FancinessSettings&gt; settings;
  
      public FancyService(ILogger&lt;FancyService&gt; logger, IOptions&lt;FancinessSettings&gt; settings)
      {
          this.logger = logger;
          this.settings = settings;
      }
  
      public bool IsEnabled { get; private set; }
  
      public void Initialize()
      {
          // do the initialization work and set IsEnabled to some value
      }
  }
  
  </code></pre>
  
  <p>As demonstrated in the example files, <code>loggingBuilder.AddEventLog(loggingConfiguration)</code> depends on <code>IFancyService.IsEnabled</code> that is set when <code>IFancyService.Initialize()</code> is called.</p>
  
  <p>To do that, I need access to an instance of <code>IFancyService</code>; is there a way to achieve this?</p>