Nuuvify.CommonPack.BackgroundService 2.1.0-test.25092903

This is a prerelease version of Nuuvify.CommonPack.BackgroundService.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Nuuvify.CommonPack.BackgroundService --version 2.1.0-test.25092903
                    
NuGet\Install-Package Nuuvify.CommonPack.BackgroundService -Version 2.1.0-test.25092903
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Nuuvify.CommonPack.BackgroundService" Version="2.1.0-test.25092903" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nuuvify.CommonPack.BackgroundService" Version="2.1.0-test.25092903" />
                    
Directory.Packages.props
<PackageReference Include="Nuuvify.CommonPack.BackgroundService" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Nuuvify.CommonPack.BackgroundService --version 2.1.0-test.25092903
                    
#r "nuget: Nuuvify.CommonPack.BackgroundService, 2.1.0-test.25092903"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Nuuvify.CommonPack.BackgroundService@2.1.0-test.25092903
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Nuuvify.CommonPack.BackgroundService&version=2.1.0-test.25092903&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Nuuvify.CommonPack.BackgroundService&version=2.1.0-test.25092903&prerelease
                    
Install as a Cake Tool

Nuuvify.CommonPack.BackgroundService

NuGet Downloads

Biblioteca para criação de serviços de background que processam mensagens do Azure Service Bus de forma robusta e com telemetria integrada.

Características

  • ✅ Classe base abstrata para implementação de workers
  • ✅ Integração completa com Azure Service Bus
  • ✅ Telemetria e observabilidade com OpenTelemetry
  • ✅ Tratamento robusto de erros
  • ✅ Configuração flexível via connection strings ou Azure credentials
  • ✅ Suporte a dead letter queue e message abandonment
  • ✅ Logging estruturado
  • ✅ Testes unitários incluídos

Instalação

dotnet add package Nuuvify.CommonPack.BackgroundService

Uso Básico

1. Implementação da Classe Concreta

public class OrderProcessingService : BackgroundServiceAbstract<OrderProcessingService>
{
    public OrderProcessingService(
        ILogger<OrderProcessingService> logger,
        IConfigurationCustom configurationCustom,
        RequestConfiguration requestConfiguration,
        ActivitySource activitySource)
        : base(logger, configurationCustom, requestConfiguration, activitySource,
               maxConcurrentCalls: 10, maxAutoLockRenewalDuration: TimeSpan.FromMinutes(10))
    {
        // Configurar comportamento em caso de falha
        AbandonMessageIfFailed = true; // ou false para usar dead letter queue
    }

    public override async Task<bool> ExecuteRule(
        ServiceBusReceivedMessage message,
        ActivitySource activitySource,
        CancellationToken cancellationToken)
    {
        using var activity = activitySource.StartActivity("ProcessOrder");

        try
        {
            // Sua lógica de processamento aqui
            var messageBody = message.Body.ToString();
            var orderData = JsonSerializer.Deserialize<OrderData>(messageBody);

            // Adicionar telemetria
            activity?.SetTag("order.id", orderData.OrderId);

            Logger.LogInformation("Processando pedido {OrderId}", orderData.OrderId);

            // Processar o pedido
            await ProcessOrderAsync(orderData, cancellationToken);

            return true; // Sucesso
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Erro ao processar mensagem {MessageId}", message.MessageId);
            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
            return false; // Falha
        }
    }

    private async Task ProcessOrderAsync(OrderData orderData, CancellationToken cancellationToken)
    {
        // Implementar lógica de negócio
        await Task.Delay(1000, cancellationToken);
    }
}

2. Configuração no appsettings.json

{
  "AppConfig": {
    "ServiceBus": {
      "Cnn": "ServiceBusConnection",
      "Topic": "orders-topic",
      "Subscription": "order-processing-subscription"
    }
  },
  "ConnectionStrings": {
    "ServiceBusConnection": "Endpoint=sb://your-namespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=your-key"
  }
}

3. Registro no DI Container

public void ConfigureServices(IServiceCollection services)
{
    // Registrar dependências
    services.AddSingleton<IConfigurationCustom, ConfigurationCustom>();
    services.AddScoped<RequestConfiguration>();
    services.AddSingleton(new ActivitySource("YourApp"));

    // Registrar o background service
    services.AddHostedService<OrderProcessingService>();
}

Configuração com Azure Credentials

Para ambientes de produção, recomenda-se usar Azure Managed Identity:

public override void ConfigureServiceBus(
    ServiceBusClientOptions serviceBusClientOptions,
    TokenCredential credential,
    ServiceBusProcessorOptions serviceBusProcessorOptions)
{
    base.ConfigureServiceBus(serviceBusClientOptions, credential, serviceBusProcessorOptions);
}

Configure no appsettings.json:

{
  "AppConfig": {
    "ServiceBus": {
      "FullyQualifiedNamespace": "your-namespace.servicebus.windows.net",
      "Topic": "orders-topic",
      "Subscription": "order-processing-subscription"
    }
  }
}

Interface IBackgroundServiceAbstract

A biblioteca fornece uma interface que define o contrato:

public interface IBackgroundServiceAbstract<T>
{
    Task<bool> ExecuteRule(
        ServiceBusReceivedMessage message,
        ActivitySource activitySource,
        CancellationToken cancellationToken);

    bool AbandonMessageIfFailed { get; set; }
}

Tratamento de Erros

A classe base trata automaticamente diferentes tipos de erros:

  • ServiceBusException: Erros específicos do Service Bus (lock perdido, quota excedida, etc.)
  • OperationCanceledException: Cancelamento de operação
  • Exception: Erros gerais

Comportamento de Falhas

Configure o comportamento quando uma mensagem falha:

// Abandonar mensagem (retorna para a fila)
AbandonMessageIfFailed = true;

// Enviar para dead letter queue (padrão)
AbandonMessageIfFailed = false;

Telemetria e Observabilidade

A classe integra automaticamente com OpenTelemetry:

  • Traces: Cada processamento de mensagem gera um trace
  • Tags: CorrelationId, dados da mensagem
  • Status: Success/Error com detalhes

Logs Estruturados

A biblioteca gera logs estruturados em vários níveis:

  • Information: Início/fim do processamento
  • Warning: Operações canceladas
  • Error: Falhas no processamento
  • Debug: Detalhes internos (quando habilitado)

Configurações Avançadas

Parâmetros do Construtor

protected BackgroundServiceAbstract(
    ILogger<BackgroundServiceAbstract<T>> logger,
    IConfigurationCustom configurationCustom,
    RequestConfiguration requestConfiguration,
    ActivitySource activitySourceCustom,
    int maxConcurrentCalls = 10,                    // Máximo de mensagens processadas simultaneamente
    TimeSpan maxAutoLockRenewalDuration = TimeSpan.FromMinutes(5)) // Tempo de renovação do lock

Propriedades Protegidas

  • Logger: Instância do logger
  • ConfigurationCustom: Configuração da aplicação
  • RequestConfiguration: Configuração da requisição
  • ActivitySourceCustom: Source para telemetria

Exemplo Completo

Veja o arquivo Examples/OrderProcessingBackgroundService.cs para um exemplo completo de implementação.

Testes

A biblioteca inclui testes unitários abrangentes. Para executar:

dotnet test test/Nuuvify.CommonPack.BackgroundService.xTest/

Dependências

  • Azure.Messaging.ServiceBus
  • Microsoft.Extensions.Hosting.Abstractions
  • Azure.Monitor.OpenTelemetry.AspNetCore
  • Nuuvify.CommonPack.Middleware.Abstraction

Licença

Este projeto está licenciado sob a licença MIT. Veja o arquivo LICENSE para detalhes.

Contribuição

Contribuições são bem-vindas! Por favor, veja o arquivo CONTRIBUTING.md para diretrizes.

Changelog

Veja o arquivo CHANGELOG.md para histórico de versões e mudanças.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.1.0-test.25100702 4 10/8/2025
2.1.0-test.25100602 10 10/6/2025
2.1.0-test.25100507 5 10/6/2025
2.1.0-test.25100505 5 10/5/2025
2.1.0-test.25100503 3 10/5/2025
2.1.0-test.25093008 16 9/30/2025
2.1.0-test.25093006 0 9/30/2025
2.1.0-test.25092903 0 9/30/2025
2.1.0-test.25071808 0 7/19/2025

CHANGELOG.md