title: Dependency Injection Serilog in .Net Framework
body: <p>I am starting a .Net Framework desktop application and I'm trying to use Dependency Injection.  I have a working example where I Inject my SettingsService into the main window.  I am trying to get logging injected into my SettingsService but when I do it throws some errors.  I've tried setting the Logger after the host creates the service and everything works great. But that's not the DI way.</p>
  <p><a href="https://i.stack.imgur.com/8P0oB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8P0oB.png" alt="enter image description here" /></a></p>
  <p>Below is the code:</p>
  <p>Uses:</p>
  <pre><code>using ReceiptApplication.Services;
  using Serilog;
  using System.Windows;
  using Microsoft.Extensions.DependencyInjection;
  using Microsoft.Extensions.Hosting;
  </code></pre>
  <p>Main:</p>
  <pre><code>public App()
  {
      //SetupLogger();
      Log.Logger = new LoggerConfiguration()
      .MinimumLevel.Information()
      .WriteTo.Console()
      .WriteTo.File(&quot;log.txt&quot;,
          rollingInterval: RollingInterval.Day,
          rollOnFileSizeLimit: true)
      .CreateLogger();
  
      Log.Information(&quot;Hello, Serilog!&quot;);
  
      Log.CloseAndFlush();
  
      _host = Host.CreateDefaultBuilder()
          .UseSerilog()
          .ConfigureServices((context, services) =&gt; {
              ConfigureServices(services);
          })
          .Build();
  }
  
  private void ConfigureServices(IServiceCollection services)
  {
      services.AddSingleton&lt;ISettingsService, SettingsService&gt;();
      services.AddSingleton&lt;newMainWindow&gt;();
  }
  
  protected override async void OnStartup(StartupEventArgs e)
  {
      await _host.StartAsync();
      // This is the line that throws the error.  
      // System.InvalidOperationException: 'Unable to resolve service for type 'Serilog.ILogger'
      // while attempting to activate 'App.Services.SettingsService.
      var newMainWindow = _host.Services.GetRequiredService&lt;newMainWindow&gt;(); 
      newMainWindow.Show();
      base.OnStartup(e);
  }
  </code></pre>
  <p>Below is the SettingsService</p>
  <pre><code>class SettingsService : ISettingsService
  {
      public static ILogger Log { get; set; }
  
      public SettingsService(ILogger log)
      {
          Log = log;
      }
  
      public void SetLog(ILogger log)
      {
          Log = log;
          Log.Debug(&quot;Log was set&quot;);
      }
  
      public void TestLog()
      {
          Log.Debug(&quot;This is a test&quot;);
      }
  
      public Settings GetSettings()
      {
          return new Settings();
      }
  
  }
  </code></pre>
  <p>Here is the SettingService Interface</p>
  <pre><code>public interface ISettingsService
  {
      Settings GetSettings();
      void SetLog(ILogger log);
      void TestLog();
  }
  </code></pre>