NotiCOO.Core.Publisher
1.0.0
dotnet add package NotiCOO.Core.Publisher --version 1.0.0
NuGet\Install-Package NotiCOO.Core.Publisher -Version 1.0.0
<PackageReference Include="NotiCOO.Core.Publisher" Version="1.0.0" />
<PackageVersion Include="NotiCOO.Core.Publisher" Version="1.0.0" />
<PackageReference Include="NotiCOO.Core.Publisher" />
paket add NotiCOO.Core.Publisher --version 1.0.0
#r "nuget: NotiCOO.Core.Publisher, 1.0.0"
#:package NotiCOO.Core.Publisher@1.0.0
#addin nuget:?package=NotiCOO.Core.Publisher&version=1.0.0
#tool nuget:?package=NotiCOO.Core.Publisher&version=1.0.0
NotiCOO.Core.Publisher
Message broker publisher wrapper library for the NotiCOO notification system.
Overview
This package provides a simple, dependency injection-friendly way to publish notifications to message brokers (currently supports RabbitMQ). It supports broker-agnostic configuration through environment variables, making it ideal for containerized and cloud deployments.
Features
- ✅ Broker-agnostic configuration for message publishing
- ✅ Currently supports RabbitMQ with extensible design for other brokers
- ✅ Environment variable configuration support
- ✅ Dependency injection integration
- ✅ Support for different message priorities
- ✅ Automatic connection and channel management
- ✅ Disposable pattern for resource cleanup
- ✅ Retry logic for failed notification deliveries
Installation
Install the package:
dotnet add package NotiCOO.Core.Publisher
Usage
Basic Setup
Add to your Program.cs
or service configuration:
using NotiCOO.Core.Publisher.Extensions;
var builder = Host.CreateApplicationBuilder(args);
// Add configuration sources including environment variables
builder.Configuration
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
// Register Publisher services with environment variable support
builder.Services.AddNotiCOOCorePublisher();
var host = builder.Build();
Using the Publisher
Basic Usage
Inject and use INotificationPublisher
in your services:
using NotiCOO.Core.Publisher.Interfaces;
using NotiCOO.Core.Models;
public class NotificationService
{
public NotificationService()
{
}
public async Task SendNotificationAsync()
{
var notification = new NotificationMessage
{
Title = "Hello World",
Body = "This is a test notification",
Priority = NotificationPriority.High
};
using (var publisher = new NotificationPublisher() ) {
// Send the notification
var messageId = publisher.SendNotification(notification);
Console.WriteLine($"Message sent with ID: {messageId}");
}
}
}
Real-World Usage Examples from NotiCOO.Consumer
Based on the production implementation in NotiCOO.Consumer.Services.PushSingleClientService
:
1. Publishing User Notifications with Retry Logic
using Microsoft.Extensions.Options;
using NotiCOO.Core.Publisher.Services;
using NotiCOO.Core.Models;
public class PushSingleClientService
{
private readonly NotiCooConfig _noticooConfig;
private const int MAX_RETRY_COUNT = 5;
public PushSingleClientService(IOptions<NotiCooConfig> notiCooConfig)
{
_noticooConfig = notiCooConfig.Value;
}
// Example: Republishing failed tokens with retry count
private async Task RepublishFailedTokens(NotificationMessage originalMessage,
NotificationResult result, int newRetryCount)
{
try
{
// Get failed tokens by matching indices
var failedTokens = new List<string>();
for (int i = 0; i < result.TokenResults.Count && i < originalMessage.DeviceTokens.Count; i++)
{
if (!result.TokenResults[i].IsSuccess)
{
failedTokens.Add(originalMessage.DeviceTokens[i]);
}
}
if (failedTokens.Any())
{
// Create new message with only failed tokens
var retryMessage = new NotificationMessage
{
MessageId = originalMessage.MessageId,
ClientId = originalMessage.ClientId,
Title = originalMessage.Title,
Body = originalMessage.Body,
ImageUrl = originalMessage.ImageUrl,
Data = new Dictionary<string, string>(originalMessage.Data),
Topic = originalMessage.Topic,
Condition = originalMessage.Condition,
Priority = NotificationPriority.High, // Retry messages should be high priority
ScheduledTime = originalMessage.ScheduledTime,
DeviceTokens = failedTokens
};
using (var publisherNotif = new NotificationPublisher(_noticooConfig))
{
// Publish the retry message with retry count
var republishResult = publisherNotif.SendUserNotification(retryMessage, newRetryCount);
// Log the republish result
if (!string.IsNullOrEmpty(republishResult))
{
Logger.LogInformation("Republished message {OriginalMessageId} with {FailedTokenCount} failed tokens (Retry {RetryCount}/{MaxRetry})",
originalMessage.MessageId, failedTokens.Count, newRetryCount, MAX_RETRY_COUNT);
}
else
{
Logger.LogError("Failed to republish message {MessageId} for retry {RetryCount}",
originalMessage.MessageId, newRetryCount);
}
}
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error republishing failed tokens for message {MessageId}", originalMessage.MessageId);
throw;
}
}
}
2. Logging Notification Results
// Example: Logging successful notifications
if (shouldAck)
{
Logger.LogInformation("Successfully processed single client message: {MessageId} for client: {ClientId}. All {TotalTokens} notifications sent successfully",
message.MessageId, message.ClientId, notificationResult.TotalTokens);
using (var publisherNotif = new NotificationPublisher(_noticooConfig))
{
publisherNotif.SendLogNotification(message, notificationResult);
}
}
else
{
// Log failures
Logger.LogWarning("Single client message processing completed with failures: {MessageId} for client: {ClientId}. Success: {SuccessCount}/{TotalTokens}, Failures: {FailureCount}",
message.MessageId, message.ClientId, notificationResult.SuccessCount, notificationResult.TotalTokens, notificationResult.FailureCount);
using (var publisherNotif = new NotificationPublisher(_noticooConfig))
{
publisherNotif.SendLogNotification(message, notificationResult);
}
}
3. Configuration Injection Pattern
// Constructor injection for NotiCooConfig
public class YourService
{
private readonly NotiCooConfig _noticooConfig;
public YourService(IOptions<NotiCooConfig> notiCooConfig)
{
_noticooConfig = notiCooConfig.Value;
}
public async Task ProcessNotificationAsync()
{
// Always use 'using' statement for proper disposal
using (var publisher = new NotificationPublisher(_noticooConfig))
{
var notification = new NotificationMessage
{
MessageId = Guid.NewGuid().ToString(),
ClientId = "client-123",
Title = "Important Update",
Body = "Your request has been processed",
Priority = NotificationPriority.High,
DeviceTokens = new List<string> { "device-token-1", "device-token-2" }
};
// Send with optional retry count
var result = publisher.SendUserNotification(notification, retryCount: 1);
if (!string.IsNullOrEmpty(result))
{
Console.WriteLine($"Notification sent successfully: {result}");
}
else
{
Console.WriteLine("Failed to send notification");
}
}
}
}
Key Methods
SendUserNotification
Publishes a notification message to the message broker queue.
string SendUserNotification(NotificationMessage message, int retryCount = 0)
- Parameters:
message
: The notification message to sendretryCount
: Optional retry count for tracking republish attempts
- Returns: Message ID if successful, empty string if failed
SendLogNotification
Logs notification results for monitoring and auditing.
void SendLogNotification(NotificationMessage message, NotificationResult result)
- Parameters:
message
: The original notification messageresult
: The result of the notification delivery attempt
Configuration
Environment Variables
The publisher supports the following environment variables with the NOTICOO_CONFIG__
prefix:
Environment Variable | Description | Default |
---|---|---|
NOTICOO_CONFIG__BrokerHost |
Message broker hostname | localhost |
NOTICOO_CONFIG__BrokerPort |
Message broker port | 5672 |
NOTICOO_CONFIG__BrokerUserName |
Message broker username | guest |
NOTICOO_CONFIG__BrokerPassword |
Message broker password | guest |
NOTICOO_CONFIG__VirtualHost |
RabbitMQ virtual host | / |
NOTICOO_CONFIG__TopicName |
Topic/Exchange name | notifications |
NOTICOO_CONFIG__QueueName |
Queue name | notification-queue |
NOTICOO_CONFIG__RoutingKey |
Routing key | notification.singleclient |
NOTICOO_CONFIG__Durable |
Queue durability | true |
NOTICOO_CONFIG__AutoDelete |
Auto-delete queue | false |
NOTICOO_CONFIG__Exclusive |
Exclusive queue | false |
NOTICOO_CONFIG__PrefetchCount |
Message prefetch count | 1 |
appsettings.json Configuration
You can also configure through appsettings.json
:
{
"NOTICOO_CONFIG": {
"BrokerHost": "rabbitmq.example.com",
"BrokerPort": 5672,
"BrokerUserName": "publisher",
"BrokerPassword": "your-password",
"VirtualHost": "/",
"TopicName": "notifications-prod",
"QueueName": "notification-queue-prod",
"RoutingKey": "notification.singleclient.prod",
"Durable": true,
"AutoDelete": false,
"Exclusive": false,
"PrefetchCount": 1
}
}
Custom Configuration
For custom configurations, you can provide your own NotiCooConfig
:
var customConfig = new NotiCooConfig
{
BrokerHost = "my-rabbitmq-server",
BrokerPort = 5672,
BrokerUserName = "myuser",
BrokerPassword = "mypassword",
TopicName = "my-exchange"
};
builder.Services.AddNotiCOOCorePublisher(customConfig);
Environment Examples
Command Line / Shell
# Set all required environment variables
export NOTICOO_CONFIG__BrokerHost="rabbitmq.example.com"
export NOTICOO_CONFIG__BrokerPort="5672"
export NOTICOO_CONFIG__BrokerUserName="publisher"
export NOTICOO_CONFIG__BrokerPassword="your-secure-password"
export NOTICOO_CONFIG__VirtualHost="/"
export NOTICOO_CONFIG__TopicName="notifications"
export NOTICOO_CONFIG__QueueName="notification-queue"
export NOTICOO_CONFIG__RoutingKey="notification.singleclient"
export NOTICOO_CONFIG__Durable="true"
export NOTICOO_CONFIG__AutoDelete="false"
export NOTICOO_CONFIG__Exclusive="false"
export NOTICOO_CONFIG__PrefetchCount="1"
# Firebase Configuration
export NOTICOO_FIREBASE__ProjectId="your-firebase-project-id"
export NOTICOO_FIREBASE__ServiceAccountKeyPath="/path/to/firebase-service-account.json"
Docker
# Environment variables for Docker containers
ENV NOTICOO_CONFIG__BrokerHost=rabbitmq
ENV NOTICOO_CONFIG__BrokerPort=5672
ENV NOTICOO_CONFIG__BrokerUserName=publisher
ENV NOTICOO_CONFIG__BrokerPassword=publisher-password
ENV NOTICOO_CONFIG__VirtualHost=/
ENV NOTICOO_CONFIG__TopicName=notifications
ENV NOTICOO_CONFIG__QueueName=notification-queue
ENV NOTICOO_CONFIG__RoutingKey=notification.singleclient
ENV NOTICOO_CONFIG__Durable=true
ENV NOTICOO_CONFIG__AutoDelete=false
ENV NOTICOO_CONFIG__Exclusive=false
ENV NOTICOO_CONFIG__PrefetchCount=1
# Firebase Configuration
ENV NOTICOO_FIREBASE__ProjectId=your-firebase-project-id
ENV NOTICOO_FIREBASE__ServiceAccountKeyPath=/app/firebase-service-account.json
Dependencies
Package | Version | Description |
---|---|---|
NotiCOO.Core |
1.0.0 | Core models and utilities |
RabbitMQ.Client |
7.1.2 | RabbitMQ .NET client library |
Microsoft.Extensions.Configuration |
9.0.6 | Configuration abstractions |
Microsoft.Extensions.Configuration.Binder |
8.0.0 | Configuration binding extensions |
Microsoft.Extensions.DependencyInjection.Abstractions |
8.0.0 | Dependency injection abstractions |
Microsoft.Extensions.Hosting.Abstractions |
8.0.0 | Hosting abstractions |
Microsoft.Extensions.Logging.Abstractions |
8.0.0 | Logging abstractions |
Microsoft.Extensions.Options |
8.0.0 | Options pattern support |
Newtonsoft.Json |
13.0.1 | JSON serialization library |
NuGet Package
Package ID: NotiCOO.Core.Publisher
Product | Versions 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. |
-
net8.0
- Microsoft.Extensions.Configuration (>= 9.0.6)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Console (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- Newtonsoft.Json (>= 13.0.1)
- NotiCOO.Core (>= 1.0.0)
- RabbitMQ.Client (>= 7.1.2)
- Serilog.Extensions.Hosting (>= 8.0.0)
- Serilog.Sinks.Console (>= 5.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
1.0.0 | 156 | 7/28/2025 |