Sindika.AspNet.Connection 1.6.3

dotnet add package Sindika.AspNet.Connection --version 1.6.3
                    
NuGet\Install-Package Sindika.AspNet.Connection -Version 1.6.3
                    
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="Sindika.AspNet.Connection" Version="1.6.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Sindika.AspNet.Connection" Version="1.6.3" />
                    
Directory.Packages.props
<PackageReference Include="Sindika.AspNet.Connection" />
                    
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 Sindika.AspNet.Connection --version 1.6.3
                    
#r "nuget: Sindika.AspNet.Connection, 1.6.3"
                    
#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 Sindika.AspNet.Connection@1.6.3
                    
#: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=Sindika.AspNet.Connection&version=1.6.3
                    
Install as a Cake Addin
#tool nuget:?package=Sindika.AspNet.Connection&version=1.6.3
                    
Install as a Cake Tool

Sindika.AspNet.Connection

Sindika.AspNet.Connection is a .NET library designed to simplify and standardize connection management for various services such as Citus, Kafka, PostgreSQL, RabbitMQ, and Redis. It provides robust tools to configure, validate, and manage these connections efficiently.


Features

  • Citus Connection Management:

    • Simplified connection setup for Citus DB.
    • Health checks to ensure availability and performance.
    • Configurable settings for database tuning.
  • Kafka Integration:

    • Streamlined connection handling for Kafka brokers.
    • Support for producer and consumer setup.
  • PostgreSQL Support:

    • Easy-to-configure connection for PostgreSQL databases.
    • Built-in health checks and validation.
  • RabbitMQ Support:

    • Efficient connection management for RabbitMQ messaging.
    • Support for queues and message validation.
  • Redis Integration:

    • Configurable connection settings for Redis caching and data storage.
    • Supports connection pooling and health checks.

Usage

Citus Connection

  1. Configuration: Use CitusSettings.cs to define the necessary settings for connecting to the Citus database.

    var settings = new CitusSettings
    {
        Host = "localhost",
        Port = 5432,
        Database = "my_database",
        Username = "user",
        Password = "password"
    };
    
  2. Connection Manager: Use CitusConnectionManager to establish and manage the connection.

    var manager = new CitusConnectionManager(settings);
    var connection = manager.GetConnection();
    
  3. Health Check: Ensure the connection is healthy using CitusHealthChecker.

    var healthChecker = new CitusHealthChecker();
    bool isHealthy = healthChecker.CheckHealth(connection);
    

RabbitMQ

1. RabbitMQ Configuration in appsettings.json

To connect the application with RabbitMQ, add the following configuration in appsettings.json or appsettings.Development.json:

"RabbitmqSettings": {
    "HostName": "rabbitmq-host",
    "Port": 5672,
    "UserName": "rabbitmq-username",
    "Password": "rabbitmq-password"
}

Note:

  • Replace rabbitmq-host, rabbitmq-username, rabbitmq-password with the appropriate RabbitMQ address.
  • Do not store sensitive credentials in the code. Use environment variables or secret manager if needed.

2. Register RabbitMQ in Program.cs

Add the following code in Program.cs to configure RabbitMQ:

using Sindika.AspNet.Connection.Rabbitmq;

var builder = WebApplication.CreateBuilder(args);

var Configuration = builder.Configuration;
Configuration.AddEnvironmentVariables();

// Register RabbitMQ Extensions
builder.Services.AddRabbitMQ(Configuration);

3. Using RabbitMQ Service
3.1 Publishing Messages

Example of publishing messages to RabbitMQ:

public class OrderService
{
    private readonly RabbitmqService _rabbitmqService;

    public OrderService(RabbitmqService rabbitmqService)
    {
        _rabbitmqService = rabbitmqService;
    }

    public async Task SendMessageAsync()
    {
        var exchangeConfig = new RabbitmqExchangeConfig
        {
            Name = "order-exchange",
            Type = ExchangeType.Direct,
            Durable = true,
            AutoDelete = false
        };

        var routingKey = "order.created";
        var message = "New order placed";

        await _rabbitmqService.PublishMessageAsync(exchangeConfig, routingKey, message);
    }
}
3.2 Consuming Messages (Background Service)

For continuous message consumption, use a BackgroundService implementation:

public class OrderConsumerService : BackgroundService
{
    private readonly RabbitmqService _rabbitmqService;
    private readonly ILogger<OrderConsumerService> _logger;
    private string? _consumerTag;

    public OrderConsumerService(
        RabbitmqService rabbitmqService,
        ILogger<OrderConsumerService> logger)
    {
        _rabbitmqService = rabbitmqService;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            var exchangeConfig = new RabbitmqExchangeConfig
            {
                Name = "order-exchange",
                Type = ExchangeType.Direct,
                Durable = true,
                AutoDelete = false
            };

            var queueConfig = new RabbitmqQueueConfig
            {
                Name = "order-queue",
                Durable = true,
                Exclusive = false,
                AutoDelete = false
            };

            var queueBindConfig = new RabbitmqQueueBindConfig
            {
                Queue = "order-queue",
                Exchange = "order-exchange",
                RoutingKey = "order.created"
            };

            // Start consuming messages
            _consumerTag = await _rabbitmqService.ConsumeMessageAsync(
                exchangeConfig,
                queueConfig,
                queueBindConfig,
                async (message) =>
                {
                    _logger.LogInformation("Received message: {Message}", message);

                    // Process your message here
                    await ProcessOrderAsync(message);
                },
                stoppingToken
            );

            _logger.LogInformation("Consumer started with tag: {ConsumerTag}", _consumerTag);

            // Keep the service running
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }
        catch (OperationCanceledException)
        {
            _logger.LogInformation("Consumer service is stopping...");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in consumer service");
            throw;
        }
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        if (!string.IsNullOrEmpty(_consumerTag))
        {
            await _rabbitmqService.StopConsumingAsync(_consumerTag, cancellationToken);
            _logger.LogInformation("Consumer stopped");
        }

        await base.StopAsync(cancellationToken);
    }

    private async Task ProcessOrderAsync(string message)
    {
        // Your business logic here
        _logger.LogInformation("Processing order: {Message}", message);
        await Task.CompletedTask;
    }
}

Register the background service in Program.cs:

builder.Services.AddHostedService<OrderConsumerService>();
3.3 Getting Single Message (Pull-based)

For scenarios where you need to fetch a single message on-demand:

public class OrderProcessingService
{
    private readonly RabbitmqService _rabbitmqService;

    public OrderProcessingService(RabbitmqService rabbitmqService)
    {
        _rabbitmqService = rabbitmqService;
    }

    public async Task<string> GetNextOrderAsync()
    {
        var exchangeConfig = new RabbitmqExchangeConfig
        {
            Name = "order-exchange",
            Type = ExchangeType.Direct,
            Durable = true
        };

        var queueConfig = new RabbitmqQueueConfig
        {
            Name = "order-queue",
            Durable = true,
            Exclusive = false,
            AutoDelete = false
        };

        var queueBindConfig = new RabbitmqQueueBindConfig
        {
            Queue = "order-queue",
            Exchange = "order-exchange",
            RoutingKey = "order.created"
        };

        // Get single message (returns empty string if no message available)
        var message = await _rabbitmqService.GetMessageAsync(
            exchangeConfig,
            queueConfig,
            queueBindConfig,
            autoAck: false // Set to true for auto-acknowledge
        );

        return message;
    }
}
3.4 Queue Management

Delete a queue when needed:

public async Task DeleteOrderQueueAsync()
{
    await _rabbitmqService.DeleteQueueAsync("order-queue");
}

4. RabbitMQ Configuration Models
RabbitmqExchangeConfig
public class RabbitmqExchangeConfig
{
    public string Name { get; set; }           // Exchange name
    public string Type { get; set; }           // Exchange type: "direct", "fanout", "topic", "headers"
    public bool Durable { get; set; }          // Survive broker restart
    public bool AutoDelete { get; set; }       // Delete when no longer in use
    public IDictionary<string, object>? Arguments { get; set; }
    public bool NoWait { get; set; }
    public CancellationToken CancellationToken { get; set; }
}
RabbitmqQueueConfig
public class RabbitmqQueueConfig
{
    public string Name { get; set; }           // Queue name
    public bool Durable { get; set; }          // Survive broker restart
    public bool Exclusive { get; set; }        // Used by only one connection
    public bool AutoDelete { get; set; }       // Delete when consumer cancels
    public IDictionary<string, object>? Arguments { get; set; }
    public bool NoWait { get; set; }
    public CancellationToken CancellationToken { get; set; }
}
RabbitmqQueueBindConfig
public class RabbitmqQueueBindConfig
{
    public string Queue { get; set; }          // Queue name to bind
    public string Exchange { get; set; }       // Exchange name to bind to
    public string RoutingKey { get; set; }     // Routing key for binding
    public IDictionary<string, object>? Arguments { get; set; }
    public bool NoWait { get; set; }
    public CancellationToken CancellationToken { get; set; }
}

5. Best Practices
  • Use BackgroundService for Consumers: Always implement consumers as BackgroundService or IHostedService for proper lifecycle management
  • Handle Cancellation Tokens: Pass CancellationToken to enable graceful shutdown
  • Error Handling: Consumer automatically handles errors with Nack and requeue mechanism
  • Auto-Recovery: Connection includes automatic recovery enabled by default
  • Durable Queues: Use Durable = true for queues that should survive broker restarts
  • Manual Acknowledgment: Use autoAck: false and manually acknowledge messages after processing to ensure reliability

Future Plans

  • Add implementation for Kafka connection management.
  • Extend PostgreSQL, RabbitMQ, and Redis connection support.
  • Provide detailed examples for each service.
  • Include performance optimization tools.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  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.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Sindika.AspNet.Connection:

Package Downloads
Sindika.AspNet.Authentication

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.6.3 106 2/1/2026
1.6.2 828 8/25/2025
1.6.1 524 8/1/2025
1.6.0 171 8/1/2025
1.5.5 480 5/14/2025
1.5.4 1,019 3/11/2025
1.5.3 368 3/10/2025
1.5.2 341 3/7/2025
1.5.1 277 3/7/2025
1.5.0 257 3/7/2025
1.4.0 176 2/26/2025
1.3.0 166 2/26/2025
1.2.1 417 2/5/2025
1.2.0 166 2/4/2025
1.1.0 166 2/4/2025
1.0.0 1,316 1/17/2025