title: "Restart" singleton service in ASP.Net Core
body: <p>I have a couple of services that I inject using DI in an ASP.Net Core App. These services use a couple of writable configuration objects that I also inject using DI. However, as these services need to be singletons, the configuration object is only passed when the service is started, any changes to it will thus not be picked up. So I need to either restart these singletons or somehow get the new <code>IOptionsSnapshot</code> passed into them.</p>
  
  <p>To further clarify, here is my code:</p>
  
  <p>Startup.cs:</p>
  
  <pre><code>//Inject service and config object
  services.ConfigureWritable&lt;DataSettings&gt;(Configuration.GetSection("DataSettings"));
  services.AddSingleton&lt;IHostedService, DataService&gt;();
  </code></pre>
  
  <p>DataService.cs:</p>
  
  <pre><code>public DataService(IOptionsSnapshot&lt;DataSettings&gt; data)                   
  {
      //_options is used to configure the service
      this._options = data.Value;
  }
  </code></pre>
  
  <p>DataController.cs:</p>
  
  <pre><code>public DataController(IWritableOptions&lt;DataSettings&gt; data)
  {
      _data = data;
  }
  
  [HttpPost("conf/data/new")]
  public void InsertData([FromBody] IEnumerable&lt;ModuleSettings&gt; newData)
  {
      var data = _data.Value.Data.ToList();
      data.AddRange(newData.ToList());
      _data.Update(d =&gt; d.Data = data.ToArray());
  }
  </code></pre>
  
  <p>As you can see, I set up my service with a config object in <em>Startup.cs</em>. Then I pass the config object to both my service and a controller used for configuring the service. The Interface <code>IWritableOptions</code> is derived from <code>IOptionsSnapshot</code> and can be used to write back the changes to <em>appsettings.json</em>. This all works, however, when I make changes to my configuration object and update <em>appsettings.json</em>, the changes do not get passed into my service. It would be overkill to restart the whole application so I am looking for a way to just restart that one service or somehow set the config object in it. I can't expose the <code>_options</code> property of the service because these services are configured dynamically so there could be 2, 3, etc. running in the background.</p>