How to use HostBuilder for WebJob?

二次信任 提交于 2020-12-08 05:42:30

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/51970969/how-to-use-hostbuilder-for-webjob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!