Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HostBuilder for WebJob?

With .Net 2.0 was introduced the really usefull HostBuilder for Console App like we have with WebHostBuilder for Web Application.

My concern is now how to implement the HostBuilder with WebJob with a QueueTrigger?

Until now, I was using JobActivator:

        var startup = new Startup();
        var serviceProvider = startup.ConfigureServices(new ServiceCollection());
        startup.Configure(serviceProvider);

        var jobHostConfiguration = new JobHostConfiguration()
        {
            JobActivator = new JobActivator(serviceProvider),
        };

        var host = new JobHost(jobHostConfiguration);
        host.RunAndBlock();

For a full sample, here is my code: https://github.com/ranouf/DotNetCore-CosmosDbTrigger-WebJob/tree/master/CosmosDbTriggerWebJob.App

Is there someone who already use HostBuilder for a WebJob with a QueueTrigger? Is it possible?

Thanks

like image 727
Cedric Arnould Avatar asked Aug 22 '18 16:08

Cedric Arnould


1 Answers

Right then, I've figured this out. Firstly ensure that you've upgraded your packages to use the latest v3 versions of the appropriate WebJob packages.

I found that I needed the following:

  1. Microsoft.Azure.WebJobs
  2. Microsoft.Azure.WebJobs.Core
  3. Microsoft.Azure.WebJobs.Extensions.ServiceBus

Then you can use the builder in your Main method for the Console project as follows:

 static async Task Main()
    {
        var builder = new HostBuilder();
        builder.ConfigureAppConfiguration(cb =>
        {
            cb.AddJsonFile("appsettings.json");
        });
        builder.ConfigureWebJobs(b =>
        {
            b.AddServiceBus();
        });
        await builder.RunConsoleAsync();
    }

Note that I've enabled the language feature 7.1 to support async Main methods. You can use 'Wait()' instead if you prefer. Then I added an appsettings.json file to my project as follows:

{
   "ConnectionStrings": {
      "AzureWebJobsServiceBus": "Endpoint=sb://..."
    }
}

(EDIT: and ensured the file is copied always to the output folder) And finally and most importantly I modified the trigger function to include the name of the Connection as follows:

    public static void ProcessQueueMessage([ServiceBusTrigger("[Your Queue Name]", Connection = "AzureWebJobsServiceBus")] string message, TextWriter log)
    {
        log.WriteLine(message);
    }

Even though the name of the Connection is the default I still seemed to have to define it in my function attributes. I tried the 'Values' approach too but I couldn't make that work. I then started receiving messages from the service bus.

like image 100
The Senator Avatar answered Oct 21 '22 08:10

The Senator