Skip to main content

Hosted Services

The Jetveo platform allows you to run hosted services in the background. To make such a service, make a class implementing the IHostedService interface.

The service must implement the two following asynchronous methods:

  • StartAsync Executes upon registering the service.
  • StopAsync Executes upon gracefully terminating the service.

The service starts when it gets registered. Typically within a startup command.

App.Services.RegisterHostedService<ExampleService>("example hosted service");
  • In the StartAsync method, initialize the service. The following is a simple example.
private async Task RunLoop(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var readonlyDb = dbProvider.CreateDbContext();
var entities = readonlyDb.ExampleEntitySet;
var count = entities.Count();

logger.Info($"There are {count} Example Entities in the database", entities);
await Task.Delay(TimeSpan.FromSeconds(15));
}
}

public async Task StartAsync(CancellationToken ct)
{
logger.Debug("Executing StartAsync");
_ = Task.Run(() => RunLoop(ct));
}

This simple loop will run in the background until the application stops.

Accessing the application data

To access the application data, your hosted service class must include attributes of the following types:

  • IJetveoDatabaseProvider<AppDatabase>
  • IJetveoLogger

Instances of these are passed to the Hosted Service constructor.

public class ExampleService : IHostedService
{
private readonly IJetveoDatabaseProvider<AppDatabase> dbProvider;
private readonly IJetveoLogger logger;

public ExampleService(IJetveoLogger logger, IJetveoDatabaseProvider<AppDatabase> dbProvider)
{
this.logger = logger;
this.dbProvider = dbProvider;
}
...

Database

To access the database, use the IJetveoDatabaseProvider method CreateDbContext(). This creates a read only database context.

To perform a write operation on the database, we recommend invoking a custom command (Accessible at App.Commands), that works with the database. To pass arguments to the command, create a new object, that is an instance of the command model. Here follows an example of this usage:

App.Commands.ExampleCommand.InvokeAsync(new LogAccessModel() { Arg1 = x, Arg2 = y, ... }, runAsUser: techUser);

Logs

To log a message, simply call a method on the IJetveoLogger object.

Accessing the hosted service from code

The Hosted Sevice instance is available through the App.Services.GetServiceRequired<ExampleService>() method.

This is useful for calling methods, that require the service to be running. (We recommend these methods to be members of the hosted service class.) For example, our service might be communicating with external devices (Sending and receiving data), and we might want to send data with a business command.