1

I have the following WebJob Function...

public class Functions
{
    [NoAutomaticTrigger]
    public static void Emailer(IAppSettings appSettings, TextWriter log, CancellationToken cancellationToken)
    {
        // Start the emailer, it will stop on dispose
        using (IEmailerEndpoint emailService = new EmailerEndpoint(appSettings))
        {
            // Check for a cancellation request every 3 seconds
            while (!cancellationToken.IsCancellationRequested)
            {
                Thread.Sleep(3000);
            }

            log.WriteLine("Emailer: Canceled at " + DateTime.UtcNow);
        }
    }
}

I have been looking at how this gets instantiated which I can do with the simple call...

host.Call(typeof(Functions).GetMethod("MyMethod"), new { appSettings = settings })

However it's got me wondering how the TextWriter and CancellationToken are included in the instantiation. I have spotted that JobHostingConfiguration has methods for AddService and I have tried to inject my appSettings using this but it has failed with the error 'Exception binding parameter'.

So how does CancellationToken get included in the instantiation and what is JobHostingConfiguration AddService used for?

Hoots
  • 1,876
  • 14
  • 23

1 Answers1

0

how does CancellationToken get included in the instantiation

You could use the WebJobsShutdownWatcher class because it has a Register function that is called when the cancellation token is canceled, in other words when the webjob is stopping.

static void Main()
{
    var cancellationToken = new WebJobsShutdownWatcher().Token;
    cancellationToken.Register(() =>
    {
        Console.Out.WriteLine("Do whatever you want before the webjob is stopped...");
    });

    var host = new JobHost();
    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

what is JobHostingConfiguration AddService used for?

Add Services: Override default services via calls to AddService<>. Common services to override are the ITypeLocator and IJobActivator.

Here is a custom IJobActivator allows you to use DI, you could refer to it to support instance methods.

Joey Cai
  • 18,968
  • 1
  • 20
  • 30