Create .NET BackgroundService dynamically and manage the lifetime

I have a background service in .NET (BackgroundService)

public class MyService<TElement, TKey, TValue> : BackgroundService 

It works find in Startup and I have set up as follows:

_serviceCollection.AddHostedService<MyService<TElement, TKey, TValue>>(); 

_serviceCollection is IServiceCollection instance.

That works fine and great.

I am authoring some test and I want to create instances of MyService Background Service dynamically based on Web API calls. I already create them in memory triggered by web API call.

I have three calls: Create, Start, and Stop. One will create the background service in memory and the other will start and stop respectively.

I have this call to start the background service.

 [HttpPost("myservice/perf/start")]         public async Task<IActionResult> StartServiceAsync(CancellationToken cancellationToken, [FromBody] ServiceParameters params)         {             await Task.Run( () => {                 // Start the consumer service if not already started                 // retrieve service instance                  var _myServiceInstance = GetMyService( params );                  _myServiceInstance .StartAsync(new CancellationToken());               });          } 

I am not sure it is working. Even though I see breakpoint in the ExecuteAsync method that belongs to my background service, I can’t step through line by line, it just disappears. I am not sure if I am starting it correctly or if it gets cancelled when the HTTP request is closed (Hence I am using new CancellationToken rather than passing the one from Controller POST call).

I want to start the background service asynchronously. I also have another Controller call to stop MyService (it will call the StopAsync call)

Am I doing something wrong?

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.