SparkToolkit 2.0.0

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

πŸ”₯ SPARK – Service Pack and Rapid Kit

SPARK is a powerful, opinionated starter toolkit for building enterprise-grade microservices with .NET 8. It provides essential configurations, integrated libraries, and best practices to accelerate development while maintaining consistency and quality across your microservices architecture.

.NET Version NuGet Version License


✨ Key Features

πŸ—οΈ Core Infrastructure

  • βœ… Centralized Configuration - Structured settings management with validation
  • 🎯 Dependency Injection - Advanced DI patterns with service discovery
  • πŸ›‘οΈ Global Exception Handling - Comprehensive error management middleware with custom exception types
  • πŸ“Š API Versioning - Built-in versioning support with Swagger/Scalar documentation

πŸ”„ Message Queues & Communication

  • 🐰 RabbitMQ Integration - Full MassTransit support with consumer discovery and quorum queues
  • πŸ“¨ Redis Pub/Sub - High-performance message publishing and subscription with automatic handler discovery
  • ⚑ Apache Kafka - Enterprise-grade streaming platform support (Confluent.Kafka)
  • 🎭 MediatR CQRS - Command/Query pattern with pipeline behaviors (Validation, Caching, Transaction)

πŸ’Ύ Data Access & Storage

  • 🐘 PostgreSQL - Entity Framework Core 9.x with advanced configurations and interceptors
  • πŸƒ MongoDB - Document database support with repository patterns and aggregation pipelines
  • πŸ”΄ Redis Caching - Distributed caching with connection multiplexing (StackExchange.Redis)
  • πŸ“‹ Repository Pattern - Abstracted data access layer with Specification pattern

πŸ” Security & Authentication

  • πŸ”‘ JWT Authentication - Token-based authentication with Bearer support
  • πŸ›‘οΈ Authorization - Role-based and policy-based access control
  • 🌐 CORS Configuration - Environment-based CORS policies

πŸ” Resilience & Reliability

  • πŸ”„ Retry Strategies - Configurable retry policies with exponential backoff using Polly
  • ⚑ Circuit Breaker - Prevent cascade failures with circuit breaker pattern
  • ⏱️ Timeout Handling - Per-attempt timeout configuration

πŸ“„ Pagination

  • πŸ“‘ Offset-based Pagination - Traditional page/size pagination
  • πŸ”— Cursor-based Pagination - Efficient cursor pagination for large datasets
  • πŸ“Š Pagination Metadata - Automatic metadata middleware

πŸ§ͺ Development & Documentation

  • πŸ“– Swagger/OpenAPI - Auto-generated API documentation with Scalar UI
  • βœ… FluentValidation - Comprehensive model validation with MediatR integration
  • πŸ—ΊοΈ AutoMapper - Object mapping with profile configurations
  • πŸ”§ Background Services - Scalable background task processing with auto-scaling workers

πŸ“¦ Installation

dotnet add package SparkToolkit

πŸš€ Quick Start

1. Basic Usage

var builder = WebApplication.CreateBuilder(args);

// Add SPARK libraries
builder.AddLibrary();

var app = builder.Build();

// Use SPARK middleware and configurations
await app.UseLibrary();

2. Configuration Setup

Add the following sections to your appsettings.json:

{
  "DocumentApiSetting": {
    "Title": "My Microservice API",
    "Description": "A powerful microservice built with SPARK"
  },
  "RedisSetting": {
    "ClientName": "MyService",
    "Host": "localhost",
    "Port": 6379,
    "User": "default",
    "Password": "your-password"
  },
  "RabbitMqSetting": {
    "Host": "localhost",
    "Username": "guest",
    "Password": "guest",
    "Port": 5672
  },
  "PostgresSetting": {
    "ConnectionString": "Host=localhost;Database=mydb;Username=postgres;Password=password",
    "CommandTimeout": 30,
    "RetryCount": 3,
    "RetryDelay": 1000
  },
  "MongoSetting": {
    "Username": "admin",
    "Password": "password",
    "Host": "localhost",
    "Port": "27017",
    "DatabaseName": "mydatabase"
  },
  "JwtSetting": {
    "SecurityKey": "your-super-secret-key-here",
    "Issuer": "your-issuer",
    "Audience": "your-audience",
    "TokenExpiry": 3600,
    "RefreshTokenExpiry": 86400
  },
  "WorkerSetting": {
    "MinWorkerCount": 1,
    "MaxWorkerCount": 10,
    "ScaleInterval": 1800,
    "TaskThresholdToScaleUp": 50,
    "TaskThresholdToScaleDown": 20
  },
  "ResilienceDefaults": {
    "RetryCount": 3,
    "BaseDelayMilliseconds": 200,
    "JitterMilliseconds": 100,
    "TimeoutPerAttemptSeconds": 5,
    "MinimumThroughput": 5,
    "FailureRatio": 1.0,
    "BreakDurationSeconds": 30
  }
}

πŸ”§ Advanced Usage

Message Queue Integration

RabbitMQ with MassTransit
builder.Services.AddMassTransitWithRabbitMq(
    builder.Configuration,
    typeof(Program).Assembly  // Consumer assemblies
);
Redis Pub/Sub
// Register Redis Pub/Sub (both publisher and subscriber)
builder.Services.AddRedisPubSub(builder.Configuration);

// Or register only publisher
builder.Services.AddRedisPublisher(builder.Configuration);

// Or register only subscriber
builder.Services.AddRedisSubscriber(builder.Configuration);

// Register message handlers from assemblies
builder.Services.AddRedisMessageHandlers(typeof(Program).Assembly);

// Or register specific handlers
builder.Services.AddRedisMessageHandler<MyMessageHandler>("my-channel");

MediatR with Behaviors

builder.Services.AddMediatr(typeof(Program).Assembly);

Includes built-in behaviors:

  • ValidationBehaviour - FluentValidation integration
  • CachingBehavior - Automatic response caching with [Cache] attribute
  • TxBehavior - Database transaction management
Command/Query Pattern
// Define a command
public class CreateUserCommand : ICommand<UserDto>
{
    public string Name { get; set; }
    public string Email { get; set; }
}

// Define a query
public class GetUserQuery : IQuery<UserDto>
{
    public Guid UserId { get; set; }
}

// Handle with caching
[Cache("users", expirationTime: 300)]
public class GetUserQueryHandler : IQueryHandler<GetUserQuery, UserDto>
{
    public async Task<UserDto> Handle(GetUserQuery request, CancellationToken cancellationToken)
    {
        // Your logic here
    }
}

Entity Framework Configuration

// Base Entity with ID
public class MyEntity : BaseEntity<Guid>
{
    public string Name { get; set; } = string.Empty;
}

// Auditable Entity with CreatedAt, UpdatedAt, Version
public class MyAuditableEntity : BaseAuditableEntity<Guid>
{
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
}

// Trackable Entity with CreatedBy, UpdatedBy
public class MyTrackableEntity : BaseTrackableEntity<Guid>
{
    public string Name { get; set; } = string.Empty;
}

// Entity Configuration
public class MyEntityConfiguration : BaseConfiguration<MyEntity, Guid>
{
    public override void Configure(EntityTypeBuilder<MyEntity> builder)
    {
        base.Configure(builder);
        
        builder.Property(e => e.Name)
               .HasMaxLength(200)
               .IsRequired();
    }
}

Repository Pattern with Specification

// Using Specification pattern for complex queries
var spec = new Specification<User>
{
    Criteria = u => u.IsActive && u.Role == "Admin",
    Includes = new List<Expression<Func<User, object>>> { u => u.Profile },
    SortBy = "CreatedAt",
    IsAscending = false,
    Page = 1,
    PageSize = 20,
    AsNoTracking = true
};

var users = await _repository.GetListAsync(spec);

// Cursor-based pagination
var cursorSpec = new Specification<User>
{
    PaginationMode = PaginationMode.Cursor,
    Cursor = "encoded-cursor-string",
    CursorKeySelector = u => u.Id,
    PageSize = 20
};

// With projection (Specification<T, TResult>)
var projectedSpec = new Specification<User, UserDto>
{
    Criteria = u => u.IsActive,
    Selector = u => new UserDto { Id = u.Id, Name = u.Name }
};

var userDtos = await _repository.GetListAsync(projectedSpec);

Resilience Pipelines

// Register resilience pipelines
builder.Services.AddResiliencePipelines(builder.Configuration);

// Use in your services
public class MyService
{
    private readonly IResiliencePipelineFactory _pipelineFactory;
    
    public async Task<T> ExecuteWithResilienceAsync<T>(Func<Task<T>> action)
    {
        var pipeline = _pipelineFactory.GetPipeline("default");
        return await pipeline.ExecuteAsync(async ct => await action(), CancellationToken.None);
    }
}

Custom Exceptions

// Available exception types
throw new BadRequestException("Invalid input", new { Field = "email" });
throw new UnauthorizedException("Invalid token");
throw new ForbiddenException("Access denied");
throw new NotFoundException("User", userId);
throw new ConflictException("User already exists");
throw new UnprocessableEntityException("Cannot process request");
throw new BusinessException("Business rule violation");
throw new ServiceUnavailableException("Service temporarily unavailable");
throw new ServerErrorException("An unexpected error occurred");

Caching Service

public class MyService
{
    private readonly ICacheService _cacheService;

    // Get cached value
    var user = await _cacheService.GetAsync<User>("user:123");
    
    // Get with type prefix
    var user = await _cacheService.GetAsync<User>("users", "123");
    
    // Set cache with expiration (in minutes)
    await _cacheService.SetAsync("user:123", user, timeCache: 60);
    
    // Set multiple values
    await _cacheService.SetAsync(dictionary, type: "users", timeCache: 60);
    
    // Remove cache
    await _cacheService.RemoveAsync("user:123");
    
    // Remove all cache by type
    await _cacheService.RemoveTypeAsync("users");
}

Background Services

// Auto-scaling background worker
builder.Services.AddHostedService<WorkerService<MyTaskQueue>>();

πŸ“ Project Structure

Spark/
β”œβ”€β”€ Core/                              # Core abstractions and models
β”‚   β”œβ”€β”€ Attributes/                    # Custom attributes (CacheAttribute, RedisMessageHandlerAttribute)
β”‚   β”œβ”€β”€ Constants/                     # Application constants
β”‚   β”‚   β”œβ”€β”€ DefaultConstant.cs
β”‚   β”‚   β”œβ”€β”€ HostConstant.cs
β”‚   β”‚   β”œβ”€β”€ PolicyType.cs
β”‚   β”‚   β”œβ”€β”€ RedisEventConstant.cs
β”‚   β”‚   β”œβ”€β”€ StorageRedis.cs
β”‚   β”‚   β”œβ”€β”€ SystemConstant.cs
β”‚   β”‚   └── UserClaimType.cs
β”‚   β”œβ”€β”€ Enums/                         # System and User enums
β”‚   β”œβ”€β”€ Extensions/                    # Extension methods
β”‚   β”‚   β”œβ”€β”€ ConstantExtension.cs
β”‚   β”‚   β”œβ”€β”€ DateTimeExtensions.cs
β”‚   β”‚   β”œβ”€β”€ EnumExtensions.cs
β”‚   β”‚   β”œβ”€β”€ ExceptionExtensions.cs     # Custom exception types
β”‚   β”‚   └── IndentityExtension.cs
β”‚   β”œβ”€β”€ Messages/                      # Centralized messages
β”‚   β”‚   β”œβ”€β”€ CommonMessages.cs
β”‚   β”‚   β”œβ”€β”€ ExceptionMessages.cs
β”‚   β”‚   └── LogMessages.cs
β”‚   β”œβ”€β”€ Models/                        # DTOs, settings, and response models
β”‚   β”‚   β”œβ”€β”€ Common/                    # ApiResponse, ErrorResponse, ErrorValidation
β”‚   β”‚   └── Settings/                  # JWTSetting, MongoSetting, PostgresSetting
β”‚   └── SeedWorks/                     # Base entities and abstractions
β”‚       β”œβ”€β”€ Abstractions/              # IEntity, IAuditableEntity, ISoftDelete, etc.
β”‚       └── Implements/                # BaseEntity, BaseAuditableEntity, BaseTrackableEntity
β”‚
└── Libraries/                         # Implementation libraries
    β”œβ”€β”€ BackgroundServices/            # Background task processing
    β”‚   β”œβ”€β”€ BackgroundTask/            # IBackgroundTaskQueue, BackgroundTaskQueue
    β”‚   β”œβ”€β”€ Settings/                  # WorkerSetting
    β”‚   └── Workers/                   # WorkerService
    β”œβ”€β”€ Cache/                         # Redis caching implementation
    β”‚   β”œβ”€β”€ Helpers/                   # ProdCacheKey
    β”‚   β”œβ”€β”€ Services/                  # CacheService
    β”‚   β”œβ”€β”€ Settings/                  # RedisSetting
    β”‚   β”œβ”€β”€ Extension.cs
    β”‚   └── ICacheService.cs
    β”œβ”€β”€ DocumentApi/                   # Swagger/OpenAPI configuration
    β”‚   β”œβ”€β”€ Settings/                  # DocumentApiSetting
    β”‚   β”œβ”€β”€ Swagger/                   # SwaggerConfig, SwaggerGenConfig
    β”‚   β”œβ”€β”€ Versions/                  # API versioning extensions
    β”‚   └── Extension.cs
    β”œβ”€β”€ EntityFramework/               # EF Core configurations
    β”‚   β”œβ”€β”€ BaseConfig/                # BaseConfiguration
    β”‚   β”œβ”€β”€ Extensions/                # AuditExtensions, ModelBuilderExtension, QueryableExtensions
    β”‚   └── Interceptors/              # AuditableEntityInterceptor
    β”œβ”€β”€ Mediatr/                       # MediatR pipeline behaviors
    β”‚   β”œβ”€β”€ Behaviors/                 # CachingBehavior, ValidationBehaviour, TxBehavior
    β”‚   β”œβ”€β”€ Contracts/                 # ICommand, IQuery, ICommandHandler, IQueryHandler, ITxRequest
    β”‚   └── Extension.cs
    β”œβ”€β”€ MessageQueues/                 # Message queue implementations
    β”‚   β”œβ”€β”€ RabbitMQ/                  # MassTransit integration
    β”‚   β”‚   β”œβ”€β”€ Options/               # RabbitMqSetting, MassTransitConfiguration
    β”‚   β”‚   β”œβ”€β”€ BaseConsumer.cs
    β”‚   β”‚   └── RabbitMqExtensions.cs
    β”‚   └── RedisPubSub/               # Redis Pub/Sub
    β”‚       β”œβ”€β”€ Options/               # RedisPubSubQueue, HandlerDiscovery, RedisPublishOptions
    β”‚       β”œβ”€β”€ Publisher/             # IRedisPublishService, RedisPublishService
    β”‚       β”œβ”€β”€ Settings/              # RedisMessage
    β”‚       β”œβ”€β”€ Subscriber/            # IRedisMessageHandler, RedisSubscriberBackgroundService
    β”‚       └── Extension.cs
    β”œβ”€β”€ Middlewares/                   # Custom middleware
    β”‚   β”œβ”€β”€ GlobalException.cs         # Global exception handling
    β”‚   β”œβ”€β”€ MiddlewareExtensions.cs
    β”‚   └── PaginationMetadataMiddleware.cs
    β”œβ”€β”€ Mongo/                         # MongoDB support
    β”‚   β”œβ”€β”€ Extensions/                # PipelineExtension
    β”‚   └── ReferenceAttribute.cs
    β”œβ”€β”€ Pagination/                    # Pagination implementation
    β”‚   β”œβ”€β”€ Helpers/                   # CursorHelper
    β”‚   β”œβ”€β”€ Implements/                # PagedList (Offset & Cursor)
    β”‚   β”œβ”€β”€ Models/                    # CursorMetadata, OffsetMetadata
    β”‚   └── IPagedList.cs
    β”œβ”€β”€ Repositories/                  # Repository pattern implementation
    β”‚   β”œβ”€β”€ Abstractions/              # ISqlRepository, IMongoRepository
    β”‚   β”œβ”€β”€ Implements/                # SqlRepository, MongoRepository
    β”‚   β”œβ”€β”€ Options/                   # Specification
    β”‚   β”œβ”€β”€ Settings/                  # QueryOption
    β”‚   └── Extension.cs               # IRepository interface
    β”œβ”€β”€ RetryStrategy/                 # Resilience with Polly
    β”‚   β”œβ”€β”€ Options/                   # ResiliencePipelineOptions
    β”‚   β”œβ”€β”€ Services/                  # IResiliencePipelineFactory, ResiliencePipelineFactory
    β”‚   β”œβ”€β”€ Settings/                  # ResilienceDefaults
    β”‚   └── Extension.cs
    β”œβ”€β”€ SystemConfig/                  # System configurations
    β”‚   └── CorsConfig.cs
    β”œβ”€β”€ DependencyInjection.cs         # Main DI setup (AddLibrary, UseLibrary)
    └── ServiceCollectionExtensions.cs # Service registration helpers

🎯 Core Concepts

Base Entities

All entities inherit from base classes providing:

  • BaseEntity<T> - Basic entity with ID
  • BaseAuditableEntity<T> - Adds CreatedAt, UpdatedAt, Version
  • BaseTrackableEntity<T> - Adds CreatedBy, UpdatedBy for user tracking
  • ISoftDelete - Interface for soft delete support

Message Handling

  • Automatic Discovery - Handlers are automatically registered via reflection
  • Typed Messages - Strong typing with ITypedMessageHandler<T>
  • Channel-based Routing - Redis Pub/Sub with channel-specific handlers
  • Resilience - Built-in retry and circuit breaker support

Caching Strategy

  • Distributed Caching - Redis-based caching with connection pooling
  • Attribute-based - Method-level caching with [Cache] attribute
  • Type-based Keys - Organize cache by type prefixes
  • Flexible Expiration - null (60 min default), 0 (indefinite), > 0 (custom minutes)

Specification Pattern

  • Criteria - Filter expressions
  • Includes - Navigation property loading
  • Sorting - Dynamic sort by property name
  • Pagination - Offset or Cursor-based
  • Projection - Select specific fields with Selector
  • No Tracking - Optimize read-only queries

πŸ“š Dependencies

Package Version Purpose
Asp.Versioning.Mvc.ApiExplorer 8.1.0 API Versioning
AutoMapper 14.0.0 Object Mapping
Confluent.Kafka 2.11.0 Kafka Support
FluentValidation 12.0.0 Model Validation
MassTransit 8.5.0 RabbitMQ Integration
MediatR 12.5.0 CQRS Pattern
Microsoft.AspNetCore.Authentication.JwtBearer 8.0.16 JWT Auth
Microsoft.EntityFrameworkCore 9.0.6 ORM
Microsoft.Extensions.Caching.StackExchangeRedis 10.0.1 Redis Caching
MongoDB.Driver 3.4.0 MongoDB Support
Npgsql.EntityFrameworkCore.PostgreSQL 9.0.4 PostgreSQL Provider
Polly 8.6.2 Resilience
Scalar.AspNetCore 2.4.13 API Documentation UI
Swashbuckle.AspNetCore 8.1.4 OpenAPI/Swagger

🌍 Environment Configuration

SPARK supports environment-specific configurations:

  • Development - Full Swagger UI with Scalar documentation
  • Production - Optimized settings with security headers
  • Staging - Balanced configuration for testing

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ†˜ Support


Built with ❀️ for the .NET community by StudyAhead

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

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
2.0.0 103 11/29/2026
1.4.6 300 7/18/2026
1.4.5 148 7/11/2026
1.4.4 141 6/20/2026
1.4.3 183 5/4/2026
1.4.2 156 3/29/2026
1.4.1 146 2/12/2026
1.4.0 170 2/1/2026
1.2.5 159 1/3/2026
1.2.4 186 12/29/2025
1.2.3 167 12/29/2025
1.2.2 167 12/28/2025
1.2.1 242 12/24/2025
1.2.0 235 12/22/2025
1.1.9 198 12/21/2025
1.1.8 199 12/13/2025
1.1.7 724 12/3/2025
1.1.6 190 11/29/2025
1.1.5 486 11/18/2025
1.1.4 479 11/17/2025
Loading failed

Initial release of SPARK - Complete microservices toolkit for .NET 8.

 🏗️ Core Infrastructure:
 - Centralized configuration with validation
 - Advanced dependency injection patterns
 - Global exception handling middleware
 - API versioning with Swagger documentation

 🔄 Message Queues & Communication:
 - RabbitMQ integration with MassTransit
 - Redis Pub/Sub messaging
 - Apache Kafka support
 - MediatR CQRS with pipeline behaviors

 💾 Data Access & Storage:
 - PostgreSQL with Entity Framework Core
 - MongoDB document database support
 - Redis distributed caching
 - Repository pattern implementation

 🔐 Security & Authentication:
 - JWT authentication with Bearer support
 - Role-based authorization
 - Environment-based CORS configuration

 🧪 Development Features:
 - Swagger/OpenAPI with Scalar UI
 - FluentValidation integration
 - AutoMapper object mapping
 - Scalable background services

 See CHANGELOG.md for detailed release notes.