sumit
sumit

Reputation: 51

Running Background service and provide REST API Interface to get data from services in .netcore

I am writing a application which have multiple endpoints e.g. (http://localhost:5000/radio, http://localhost:5000/Location etc.) for which I am creating multiple controllers.

But for each controller I want to run Background service. Each controller will be using independent service to get data whenever request comes through REST interface.

I am not sure how to run Background services in .NET Core 3.1. I am looking to derive my Service class from BackgroundService to get this functionality.

But all the service has different behavior e.g.

It will be great if anyone can provide some insight on this scenario or show some sample code.

Upvotes: 5

Views: 9012

Answers (2)

Tekkion
Tekkion

Reputation: 38

I implemented like this:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<DirectoryMonitorService>();  // Register as a singleton
builder.Services.AddHostedService(sp => sp.GetRequiredService<DirectoryMonitorService>()); // Use the singleton as a hosted service
builder.Services.AddSingleton<IDirectoryMonitorManager>(sp => sp.GetRequiredService<DirectoryMonitorService>()); // Same instance for the manager
builder.Services.Configure<MonitoringSettings>(builder.Configuration.GetSection("MonitoringSettings"));
builder.Services.AddSingleton<MonitoringSettingsManager>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

DirectoryMonitorService uses BackgroundService class:

public class DirectoryMonitorService : BackgroundService, IDirectoryMonitorManager

Web Controller to control service:

    public class RestartController : ControllerBase
{
    private readonly IDirectoryMonitorManager _monitorService;
    private MonitoringSettingsManager _settings;
    public RestartController(IDirectoryMonitorManager monitorService, MonitoringSettingsManager settings)
    {
        _monitorService = monitorService;
        _settings = settings;
    }

    [HttpGet("GetSettings")]
    public IActionResult GetSettings()
    {
        return Ok(_settings.GetSettings());
    }

    [HttpPost("apply_new_settings")]
    public IActionResult RestartService([FromBody] MonitoringSettings settings)
    {
        if (settings != null && !settings.Equals(_settings.GetSettings()))
        {
            _monitorService.Restart(settings);
            return Ok(new { message = "Settings applied and service restarted!" });
        }
        else
            return Ok(new { message = "No change!" });
    }
}

this way I was also able to control the service lifetime from the webcontroller which was a feature i was trying to implement.

Upvotes: 0

Rosco
Rosco

Reputation: 2474

There is a good article in the docs that goes over how to setup background tasks with IHostedService and BackgroundService.

There is also a .NET Core library called Hangfire for working with background tasks which might help.

Upvotes: 4

Related Questions