title: Memory leak due to undetached events inside BackgroundService
body: <p>I have a memory leak caused by the code below, probably due to undetached events, and I don't know how to properly unsubscribe from them.</p>
  <p>I have the interface <strong>IEventsHandler</strong>, declared as singleton, which exposes some events. This interface is used inside a <strong>BackgroundService</strong>, where a subscriber is attached to the event. When an <strong>AlertEvent</strong> occurs, a scope is created to use a service which stores the event inside the database.</p>
  <p>Here is the code:</p>
  <pre><code>public class MyWorker : BackgroundService
  {
      private readonly IEventsHandler _eventsHandler;
      private readonly IServiceProvider _serviceProvider;
  
      public MyWorker(IEventsHandler eventsHandler,
                      IServiceProvider serviceProvider)
      {
          _eventsHandler = eventsHandler;
          _serviceProvider = serviceProvider;
          _eventsHandler.AlertOccurred += AlertEventOccurred;
      }
  
      private async void AlertEventOccurred(object sender, AlertEvent e)
      {
          using var scope = _serviceProvider.CreateScope();
          var service = scope.ServiceProvider.GetRequiredService&lt;AlertService&gt;();
          await service.SaveAlert(e);
      }
  }
  
  public interface IEventsHandler
  {
      event EventHandler&lt;AlertEvent&gt; AlertOccurred;
      Task AddAlertEventAsync(AlertEvent ev);
  }
  
  public class EventsHandler : IEventsHandler
  {
      public event EventHandler&lt;AlertEvent&gt; AlertOccurred;
      
      public async Task AddAlertEventAsync(AlertEvent ev)
      {
          await Task.Run(() =&gt; AlertOccurred?.Invoke(this, ev));
      }
  }
  </code></pre>
  <p>PS any advice on bad practices used in the example code is welcome :-)</p>
  <p>Thanks</p>