Search code examples
c#azureworkerservicebusazure-functions-isolated

ServicebusTrigger not recognised after upgrade wizard to .net ver 8


In the following code the keyword ServicebusTrigger is not recognised. To my understanding webjobs packages are not used for worker isolated, so am reluctant to install. How do I refactor for worker isolated?

    public async Task PublishBuildingsDifferences(
        [ActivityTrigger] IEnumerable<Difference> differences,
        [ServiceBusTrigger("%ServiceBusBuildingsTopic%", Connection = "ServiceBusConnectionString")] IAsyncCollector<string> collector)
    {
        try
        {
            using (var timer = new MetricTimer(this.telemetryClient, TelemetryConstants.BuildingsPublishDifferencesTime))
            {
                foreach (var difference in differences)
                {
                    await collector.AddAsync(difference.ToServiceBusMessage());
                }

                await collector.FlushAsync();

                this.telemetryClient.TrackTrace(TelemetryConstants.BuildingsDifferencesPublished, new Dictionary<string, string>()
                {
                    { "Total records", differences.Count().ToString() },
                });
            }
        }
        catch (Exception e)
        {
            httpClientService.HttpPostErrorHandlingFunctionApp(config, "", e, 1, IssueType.Integration);
            var wrapped = new PublishDifferencesException(e);
            this.telemetryClient.TrackException(wrapped);

            throw wrapped;
        }
    }

I have not installed Webjobs as I believe it is not used for worker isolated


Solution

  • To use ServiceBusTrigger in .NET8 isolated function, you need to have below packages in .csproj file.

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <AzureFunctionsVersion>v4</AzureFunctionsVersion>
        <OutputType>Exe</OutputType>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
        <RootNamespace>_78448810</RootNamespace>
      </PropertyGroup>
      <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.22.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.1.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.2.1" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.ServiceBus" Version="5.18.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.3-preview1" />
        <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
        <PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
      </ItemGroup>
      <ItemGroup>
        <None Update="host.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
        <None Update="local.settings.json">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
          <CopyToPublishDirectory>Never</CopyToPublishDirectory>
        </None>
      </ItemGroup>
      <ItemGroup>
        <Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
      </ItemGroup>
    </Project>
    

    I have created a default service bus topic triggered .NET8 isolated function.

    using System;
    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Extensions.Logging;
    
    namespace _78448810
    {
        public class Function1
        {
            private readonly ILogger<Function1> _logger;
    
            public Function1(ILogger<Function1> logger)
            {
                _logger = logger;
            }
    
            [Function("PublishBuildingsDifferences")]
            public async Task Run(
                [ServiceBusTrigger("mytopic", "mysubscription", Connection = "ServiceBusConnectionString")]
                ServiceBusReceivedMessage message,
                ServiceBusMessageActions messageActions)
            {
                _logger.LogInformation("Message ID: {id}", message.MessageId);
                _logger.LogInformation("Message Body: {body}", message.Body);
                _logger.LogInformation("Message Content-Type: {contentType}", message.ContentType);
    
                 // Complete the message
                await messageActions.CompleteMessageAsync(message);
            }
        }
    }
    

    I am able to get the expected response.

    Azure Functions Core Tools
    Core Tools Version:       4.0.5700 Commit hash: N/A +71cc84964a60bfb07d95839b7c666bd239507bdd (64-bit)
    Function Runtime Version: 4.33.2.22572
    
    [2024-05-08T14:27:45.848Z] Found C:\Users\******\78448810\78448810\78448810.csproj. Using for user secrets file configuration.
    [2024-05-08T14:27:53.084Z] Azure Functions .NET Worker (PID: 26540) initialized in debug mode. Waiting for debugger to attach...
    [2024-05-08T14:27:53.164Z] Worker process started and initialized.
    
    Functions:
    
            PublishBuildingsDifferences: serviceBusTrigger
    
    For detailed output, run func with --verbose flag.
    [2024-05-08T14:27:58.731Z] Host lock lease acquired by instance ID '000000000000000000000000BF6D1ED5'.
    [2024-05-08T14:33:11.038Z] Executing 'Functions.PublishBuildingsDifferences' (Reason='(null)', Id=ddd5aed0-4f33-4c28-aca2-2e3032f4dab4)
    [2024-05-08T14:33:11.044Z] Trigger Details: MessageId: 7afa352c194d493fbbedf120e33eaaa2, SequenceNumber: 1, DeliveryCount: 1, EnqueuedTimeUtc: 2024-05-08T14:33:09.6240000+00:00, LockedUntilUtc: 2024-05-08T14:34:09.6240000+00:00, SessionId: (null)
    [2024-05-08T14:33:11.642Z] Message Content-Type: (null)
    [2024-05-08T14:33:11.642Z] Message ID: 7afa352c194d493fbbedf120e33eaaa2
    [2024-05-08T14:33:11.642Z] Message Body: Hello
    [2024-05-08T14:33:11.676Z] Start processing HTTP request POST http://127.0.0.1:62483/Settlement/Complete
    [2024-05-08T14:33:11.677Z] Sending HTTP request POST http://127.0.0.1:62483/Settlement/Complete
    [2024-05-08T14:33:12.256Z] Received HTTP response headers after 564.2506ms - 200
    [2024-05-08T14:33:12.259Z] End processing HTTP request after 597.7928ms - 200
    [2024-05-08T14:33:12.369Z] Executed 'Functions.PublishBuildingsDifferences' (Succeeded, Id=ddd5aed0-4f33-4c28-aca2-2e3032f4dab4, Duration=1446ms)