SparkToolkit 1.2.2
See the version list below for details.
dotnet add package SparkToolkit --version 1.2.2
NuGet\Install-Package SparkToolkit -Version 1.2.2
<PackageReference Include="SparkToolkit" Version="1.2.2" />
<PackageVersion Include="SparkToolkit" Version="1.2.2" />
<PackageReference Include="SparkToolkit" />
paket add SparkToolkit --version 1.2.2
#r "nuget: SparkToolkit, 1.2.2"
#:package SparkToolkit@1.2.2
#addin nuget:?package=SparkToolkit&version=1.2.2
#tool nuget:?package=SparkToolkit&version=1.2.2
π₯ 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.
β¨ 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
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
π License
This project is licensed under the MIT License - see the LICENSE file for details.
π Support
- π§ Email: support.study@gmail.com
- π Website: max-h.vercel.app
- π¦ NuGet: SparkToolkit
Built with β€οΈ for the .NET community by StudyAhead
| 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
- Asp.Versioning.Mvc.ApiExplorer (>= 8.1.0)
- AutoMapper (>= 14.0.0)
- Confluent.Kafka (>= 2.11.0)
- FluentValidation (>= 12.0.0)
- FluentValidation.DependencyInjectionExtensions (>= 12.0.0)
- MassTransit (>= 8.5.0)
- MassTransit.RabbitMQ (>= 8.5.0)
- MediatR (>= 12.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.16)
- Microsoft.EntityFrameworkCore (>= 9.0.6)
- Microsoft.EntityFrameworkCore.Abstractions (>= 9.0.6)
- Microsoft.EntityFrameworkCore.Relational (>= 9.0.6)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 10.0.1)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.5)
- MongoDB.Bson (>= 3.4.0)
- MongoDB.Driver (>= 3.4.0)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 9.0.4)
- Polly (>= 8.6.2)
- Scalar.AspNetCore (>= 2.4.13)
- Swashbuckle.AspNetCore (>= 8.1.4)
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 |
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.