title: .NET Worker Service Linux Daemon Singleton
body: <p>I am creating a Linux (Ubuntu systemd) daemon in .NET 5+ Using the recently added(ish) Worker Service template.</p>
  <p>This daemon will run let’s say every few minutes, but I want the latest daemon to exit if the last execution of the daemon is still running so they don’t interfere with each other.</p>
  <p>I would normally use a singleton for this (I still will be) but I’m not sure how the .NET Worker Service is scaffolded so to speak without sifting through lots of source code.</p>
  <p>Is it already a Singleton ????</p>
  <p>This implies that it is:</p>
  <p><a href="https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/ServiceCollectionHostedServiceExtensions.cs#L19" rel="nofollow noreferrer">https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/ServiceCollectionHostedServiceExtensions.cs#L19</a></p>
  <p>Is the</p>
  <pre><code>services.AddSingleton&lt;Worker&gt;
  </code></pre>
  <p>a valid thing here ????</p>
  <p>I’m guessing I would put it somewhere within the Main call within Program.cs ????</p>
  <p>Do I need to add anything special to any exit code ????</p>
  <p>Just for interest the actual daemon checks a directory for uploaded / completed files. Gets a list of them all and moves them all somewhere else (deleting the old ones). Only one daemon should be doing this at any time.</p>
  <p>My question comes from the fact that there seems to be a lot going on with Worker Services but not many real examples I can find.</p>
  <p><a href="https://docs.microsoft.com/en-us/dotnet/core/extensions/workers" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/core/extensions/workers</a></p>
  <pre class="lang-cs prettyprint-override"><code>public class Program
  {
      public static void Main(string[] args)
      {
          CreateHostBuilder(args).Build().Run();
      }
  
      public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
          Host.CreateDefaultBuilder(args)
              .UseSystemd()
              .ConfigureServices((hostContext, services) =&gt;
              {
                  services.AddHostedService&lt;Worker&gt;();
              });
  }
  </code></pre>
  <p>.NET is moving so quickly that most information and examples are out of date and simply just wrong. It's hard to know where its at.</p>