Appearance
Configuration
For the standard host setup, use the configuration facade. It binds the GrydNotifications section and resolves the database connection through its documented fallback keys:
csharp
using GrydNotifications;
builder.Services.AddGrydNotifications(builder.Configuration);The options callback overload is also available for explicit configuration. It does not read the configuration section or resolve the facade's connection-string fallbacks, so set storage options directly when using it:
csharp
builder.Services.AddGrydNotifications(options =>
{
options.UsePostgreSqlStorage(builder.Configuration.GetConnectionString("GrydNotifications")!);
// Configure other options here.
});GrydNotificationsOptions
Connection String
Required. PostgreSQL connection string for notification persistence and template storage.
csharp
options.UsePostgreSqlStorage("Host=localhost;Database=gryd_notifications;...");
// or
options.ConnectionString = "Host=localhost;Database=gryd_notifications;...";Feature Toggles
| Property | Type | Default | Description |
|---|---|---|---|
EnableTemplates | bool | true | Enables Scriban template engine |
EnableQueue | bool | true | Enables async queue processing. When false, sends synchronously |
PersistNotifications | bool | true | Persists notifications in the database for auditing |
NotificationRetentionDays | int | 90 | Days to retain sent/failed notifications before cleanup |
csharp
options.EnableTemplates = true;
options.EnableQueue = true;
options.PersistNotifications = true;
options.NotificationRetentionDays = 90;Email Options
Configure email sending via SMTP (MailKit). When SmtpHost is empty the module registers a failure-returning fallback; it does not report a successful send. SmtpUseSsl=true selects STARTTLS on the configured port.
csharp
options.Email.DefaultFrom = "noreply@myapp.com";
options.Email.DefaultFromName = "My Application";
options.Email.SmtpHost = "smtp.myapp.com";
options.Email.SmtpPort = 587;
options.Email.SmtpUseSsl = true;
options.Email.SmtpUsername = "<smtp username>";
options.Email.SmtpPassword = configuration["Smtp:Password"]!;Properties
| Property | Type | Default | Description |
|---|---|---|---|
DefaultFrom | string | "" | Default sender email address |
DefaultFromName | string? | null | Default sender display name |
SmtpHost | string? | null | SMTP server hostname |
SmtpPort | int | 587 | SMTP server port |
SmtpUseSsl | bool | true | Use STARTTLS (SecureSocketOptions.StartTls) |
SmtpUsername | string? | null | SMTP authentication username |
SmtpPassword | string? | null | SMTP authentication password |
MaxAttachmentSizeMb | int | 10 | Maximum attachment size per email (MB), checked when the file is attached |
MaxAttachmentsPerEmail | int | 5 | Maximum number of attachments per email |
MaxRecipientsPerEmail | int | 50 | Maximum recipients (To + Cc + Bcc) |
BulkBatchSize | int | 100 | Emails per batch in bulk operations |
BulkDelayBetweenBatches | TimeSpan | 1s | Rate limiting delay between batches |
Using SendGrid instead of SMTP
To use SendGrid's HTTP API instead of SMTP, install GrydNotifications.Infrastructure.SendGrid and register its provider after AddGrydNotifications:
csharp
// Install: dotnet add package GrydNotifications.Infrastructure.SendGrid
using GrydNotifications.Infrastructure.SendGrid;
builder.Services.AddGrydNotificationsSendGrid(options =>
{
options.ApiKey = builder.Configuration["SendGrid:ApiKey"]!;
});The API key should come from a secret provider. This extension replaces the configured IEmailSender; it does not use SMTP credentials.
EventWebhookPublicKey, EventWebhookTimestampTolerance (default 5 minutes) and EventWebhookMaxBodyBytes (default 1 MiB) configure the signed Event Webhook receiver. See Delivery feedback.
Push Notification Options
Options of the push channel. Push.Enabled does not register a provider: reference GrydNotifications.Infrastructure.Firebase and call AddGrydNotificationsFirebase, or register your own IPushNotificationSender (see Channels).
csharp
options.Push.Enabled = true;
options.Push.DefaultTimeToLive = TimeSpan.FromHours(24);
options.Push.AutoRemoveInvalidTokens = true;
options.Push.RequireProvider = true;Properties
| Property | Type | Default | Description |
|---|---|---|---|
Enabled | bool | true | Enables the push channel and the stale-token cleanup |
DefaultTimeToLive | TimeSpan | 24h | TTL of a message that sets none (Android and browser) |
MaxDeviceTokensPerMulticast | int | 500 | Tokens per provider batch (FCM caps it at 500) |
StaleTokenThreshold | TimeSpan | 90 days | A token neither registered again nor used for this long is deactivated; a never-used token counts from its registration |
AutoRemoveInvalidTokens | bool | true | Deactivates tokens the provider reports as unregistered |
RequireProvider | bool | false | Fails the host start while push is enabled and no provider is registered; off, the host logs a warning |
Firebase Configuration
AddGrydNotificationsFirebase needs CredentialJson or CredentialPath (the service account); the GOOGLE_APPLICATION_CREDENTIALS variable alone is not enough. FirebaseOptions.MaxDeviceTokensPerMulticast and FirebaseOptions.AutoRemoveInvalidTokens still apply: the lower batch size wins, and either flag turns removal off.
In-App Notification Options
Configure the in-app notification channel (drawer/bell notifications + SignalR real-time).
csharp
options.InApp.Enabled = true;
options.InApp.EnableSignalR = true;
options.InApp.HubPath = "/hubs/notifications";
options.InApp.RetentionDays = 90;
options.InApp.MaxUnreadPerUser = 200;Properties
| Property | Type | Default | Description |
|---|---|---|---|
Enabled | bool | true | Enables in-app notification channel |
RetentionDays | int | 90 | Days to retain in-app notifications |
MaxUnreadPerUser | int | 200 | Max unread per user (oldest auto-marked as read) |
DefaultTimeToLive | TimeSpan? | null | Default TTL for notifications (null = no expiration) |
EnableSignalR | bool | true | Enables real-time delivery via SignalR |
HubPath | string | /hubs/notifications | SignalR hub endpoint path |
Retry Options
Configure retry policies for failed notification delivery.
csharp
options.Retry.MaxRetries = 3;
options.Retry.BackoffType = BackoffType.Exponential;
options.Retry.BaseDelay = TimeSpan.FromSeconds(5);
options.Retry.MaxDelay = TimeSpan.FromMinutes(5);
options.Retry.UseJitter = true;Properties
| Property | Type | Default | Description |
|---|---|---|---|
MaxRetries | int | 3 | Used by the registered Polly policy; the default queue budget comes from the notification command/entity |
BackoffType | BackoffType | Exponential | Backoff strategy |
BaseDelay | TimeSpan | 5s | Base delay for the first retry |
MaxDelay | TimeSpan | 5min | Final delay cap, including jitter; maximum supported value is 4,294,967,294 ms |
UseJitter | bool | true | Varies each retry delay by up to ±25% before the final cap |
NonRetryableReasons | HashSet<DeliveryFailureReason> | see below | Failure reasons that dead-letter without retry in the default queue |
For the default queue, SendNotificationCommand.MaxRetries is copied to the notification entity and controls its attempt budget. It defaults to 3; RetryCount counts failed sends, so 3 allows three total sends, while 0 or 1 allows only the initial send. Retry.MaxRetries does not override this entity budget.
Backoff Types
| Type | Formula | Example (5s base) |
|---|---|---|
Fixed | baseDelay | 5s → 5s → 5s |
Linear | baseDelay × completedFailures | 5s → 10s → 15s |
Exponential | baseDelay × 2^(completedFailures-1) | 5s → 10s → 20s |
The first retry uses BaseDelay. The default processor waits inside a bounded queue worker slot and waits for the entire current batch before dequeuing the next one. A backoff can therefore hold up later batches even when another slot is idle. Stopping during the wait leaves the record Queued without an in-memory queue entry. The volatile queue has no restart recovery scan; enable durable delivery from the start for outbox recovery. The channel sender classifies a recipient refused during the SMTP conversation: 5xx as Bounced and 4xx as ProviderUnavailable. Other provider failures are still Unknown.
Non-Retryable Failure Reasons
By default, these permanent failures skip retry entirely:
InvalidRecipient— Email address doesn't existBounced— The server definitively refused the recipient (5xx)InvalidTemplate— Template syntax errorAuthenticationFailed— Provider credential error
Queue Options
Configure the in-memory notification processing queue (Channel<T>).
csharp
options.Queue.BatchSize = 10;
options.Queue.PollingInterval = TimeSpan.FromSeconds(5);
options.Queue.MaxConcurrency = 4;Properties
| Property | Type | Default | Description |
|---|---|---|---|
BatchSize | int | 10 | Notifications dequeued per batch |
PollingInterval | TimeSpan | 5s | Polling interval when queue is empty |
MaxConcurrency | int | 4 | Concurrent processors consuming the queue |
MessageExpiration | TimeSpan? | null | Max time in queue before discard (null = no limit) |
WARNING
The default queue uses Channel<T> in-memory and has no restart recovery. Durable delivery is a separate opt-in PostgreSQL outbox mode: set DurableDelivery = true while keeping PersistNotifications and EnableQueue enabled, apply the durable migration, and register the worker profile. See Durable delivery. The optional GrydNotifications.Scheduling package integrates recurring scheduled jobs with GrydJobs; it does not enable outbox durability.
Health Checks
csharp
using GrydNotifications.API;
builder.Services.AddGrydNotificationsHealthChecks();The check reads the depth of the optional INotificationQueue, when one is registered. A depth above 10,000 or a queue read failure uses the registration's failureStatus. The default is Degraded; ASP.NET Core maps Degraded to HTTP 200 and Unhealthy to HTTP 503 by default. See ASP.NET Core health check status code mapping. Without a registered queue, the check reports that the notifications module is running. These results do not verify SMTP delivery, SignalR connectivity, database connectivity or schema, or background worker liveness.
For a readiness endpoint that fails when the queue is over the threshold or cannot be read, add the ready tag explicitly and choose Unhealthy. The default tags do not include ready:
csharp
using GrydNotifications.API;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
builder.Services.AddGrydNotificationsHealthChecks(
failureStatus: HealthStatus.Unhealthy,
tags: ["grydnotifications", "notifications", "ready"]);
app.MapHealthChecks("/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
});With ASP.NET Core's default response writer, the response body is the overall status as plain text (Healthy, Degraded, or Unhealthy). Configure a ResponseWriter explicitly if the host needs JSON details for individual checks.
appsettings.json Reference
Complete configuration example:
json
{
"ConnectionStrings": {
"GrydNotifications": "Host=localhost;Database=gryd_notifications;Username=postgres;Password=postgres"
},
"GrydNotifications": {
"EnableTemplates": true,
"EnableQueue": true,
"PersistNotifications": true,
"NotificationRetentionDays": 90,
"Email": {
"DefaultFrom": "noreply@myapp.com",
"DefaultFromName": "My App",
"SmtpHost": "smtp.example.com",
"SmtpPort": 587,
"SmtpUseSsl": true,
"SmtpUsername": "<smtp username>",
"SmtpPassword": "<load from a secret provider>",
"MaxAttachmentSizeMb": 10,
"MaxAttachmentsPerEmail": 5,
"MaxRecipientsPerEmail": 50,
"BulkBatchSize": 100,
"BulkDelayBetweenBatches": "00:00:01"
},
"Push": {
"Enabled": false,
"DefaultTimeToLive": "24:00:00",
"MaxDeviceTokensPerMulticast": 500,
"StaleTokenThreshold": "90.00:00:00",
"AutoRemoveInvalidTokens": true,
"RequireProvider": false
},
"InApp": {
"Enabled": true,
"RetentionDays": 90,
"MaxUnreadPerUser": 200,
"DefaultTimeToLive": null,
"EnableSignalR": true,
"HubPath": "/hubs/notifications"
},
"Retry": {
"MaxRetries": 3,
"BackoffType": "Exponential",
"BaseDelay": "00:00:05",
"MaxDelay": "00:05:00",
"UseJitter": true
},
"Queue": {
"BatchSize": 10,
"PollingInterval": "00:00:05",
"MaxConcurrency": 4,
"MessageExpiration": null
}
}
}