ThacoCore.Common
1.2.2
See the version list below for details.
dotnet add package ThacoCore.Common --version 1.2.2
NuGet\Install-Package ThacoCore.Common -Version 1.2.2
<PackageReference Include="ThacoCore.Common" Version="1.2.2" />
<PackageVersion Include="ThacoCore.Common" Version="1.2.2" />
<PackageReference Include="ThacoCore.Common" />
paket add ThacoCore.Common --version 1.2.2
#r "nuget: ThacoCore.Common, 1.2.2"
#addin nuget:?package=ThacoCore.Common&version=1.2.2
#tool nuget:?package=ThacoCore.Common&version=1.2.2
MainCore.Package - Thaco Core Microservices Base Package
Tổng quan
MainCore.Package là một thư viện cơ sở cho hệ thống microservices, cung cấp các chức năng phổ biến và cần thiết cho việc phát triển microservices như caching, querying, message queue, email, notification và nhiều tính năng khác.
Tính năng chính
🚀 Core Services
- Cache Service: Hỗ trợ Redis và In-Memory caching với compression
- Query Service: Tích hợp Entity Framework Core và Dapper cho database operations
- Message Queue Service: Hỗ trợ RabbitMQ và Redis cho message queuing
- Email Service: Gửi email với template, attachments và bulk operations
- Notification Service: Multi-channel notifications (Email, Push, SMS, In-App, Webhook)
🛡️ Security & Performance
- JWT Authentication: Token-based authentication với refresh token
- Rate Limiting: Giới hạn request per IP/User/Global
- DDoS Protection: Bảo vệ khỏi các cuộc tấn công DDoS
- CORS: Cross-Origin Resource Sharing configuration
- CSP: Content Security Policy headers
- Global Exception Handling: Xử lý exception toàn cục
📊 Monitoring & Logging
- Prometheus Metrics: Thu thập metrics cho monitoring
- Health Checks: Kiểm tra sức khỏe của services
- Structured Logging: Logging với Serilog
- Performance Monitoring: Theo dõi performance của queries và requests
🔧 Optimization
- Database Optimization: Connection pooling, retry logic
- Response Compression: Nén response để giảm bandwidth
- Multi-level Caching: Cache ở nhiều tầng
- Async Operations: Tất cả operations đều async
Cài đặt
1. Thêm Package Reference
<PackageReference Include="MainCore.Package" Version="1.0.0" />
2. Cấu hình trong Program.cs
using MainCore.Package.Extensions;
using MainCore.Package.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Thêm configuration
builder.Configuration.AddJsonFile("appsettings.common.json", optional: false);
// Đăng ký services
builder.Services.AddCommonServices(builder.Configuration);
builder.Services.AddCacheService(builder.Configuration);
builder.Services.AddQueryService<YourDbContext>(builder.Configuration);
builder.Services.AddEmailService(builder.Configuration);
builder.Services.AddNotificationService(builder.Configuration);
builder.Services.AddMessageQueueService(builder.Configuration);
// Thêm optimization services
builder.Services.AddOptimizationServices(builder.Configuration);
builder.Services.AddSecurityServices(builder.Configuration);
builder.Services.AddMonitoringServices(builder.Configuration);
var app = builder.Build();
// Sử dụng middleware
app.UseSecurityMiddleware();
app.UsePerformanceMiddleware();
app.UseGlobalExceptionMiddleware();
app.Run();
3. Cấu hình appsettings.json
Sao chép nội dung từ appsettings.common.json
và điều chỉnh theo môi trường của bạn.
Sử dụng Services
Cache Service
public class ProductService
{
private readonly ICacheService _cacheService;
public ProductService(ICacheService cacheService)
{
_cacheService = cacheService;
}
public async Task<Product> GetProductAsync(int id)
{
var cacheKey = $"product:{id}";
var product = await _cacheService.GetAsync<Product>(cacheKey);
if (product == null)
{
product = await GetProductFromDatabase(id);
await _cacheService.SetAsync(cacheKey, product, TimeSpan.FromMinutes(30));
}
return product;
}
}
Query Service
public class UserRepository
{
private readonly IQueryService _queryService;
public UserRepository(IQueryService queryService)
{
_queryService = queryService;
}
// Entity Framework operations
public async Task<User> GetUserByIdAsync(int id)
{
return await _queryService.GetByIdAsync<User>(id);
}
// Raw SQL operations
public async Task<IEnumerable<User>> GetActiveUsersAsync()
{
return await _queryService.QueryAsync<User>(
"SELECT * FROM Users WHERE IsActive = @IsActive",
new { IsActive = true }
);
}
// Pagination
public async Task<PagedResult<User>> GetUsersPagedAsync(int page, int size)
{
return await _queryService.GetPagedAsync<User>(page, size);
}
}
Email Service
public class NotificationController : ControllerBase
{
private readonly IEmailService _emailService;
public NotificationController(IEmailService emailService)
{
_emailService = emailService;
}
[HttpPost("send-welcome")]
public async Task<IActionResult> SendWelcomeEmail([FromBody] WelcomeRequest request)
{
var emailRequest = new EmailRequest
{
To = request.Email,
Subject = "Welcome to Thaco Core",
Body = $"Hello {request.Name}, welcome to our platform!",
IsHtml = true
};
await _emailService.SendEmailAsync(emailRequest);
return Ok();
}
[HttpPost("send-template")]
public async Task<IActionResult> SendTemplateEmail([FromBody] TemplateRequest request)
{
await _emailService.SendTemplateEmailAsync(
"WelcomeEmail",
request.Email,
new { Name = request.Name, CompanyName = "Thaco" }
);
return Ok();
}
}
Message Queue Service
public class OrderService
{
private readonly IMessageQueueService _messageQueue;
public OrderService(IMessageQueueService messageQueue)
{
_messageQueue = messageQueue;
}
public async Task ProcessOrderAsync(Order order)
{
// Publish order created event
await _messageQueue.PublishAsync("order.created", order);
// Subscribe to order events
await _messageQueue.SubscribeAsync<Order>("order.created", async (message) =>
{
// Process order
await ProcessOrderInternal(message);
});
}
}
Notification Service
public class UserService
{
private readonly INotificationService _notificationService;
public UserService(INotificationService notificationService)
{
_notificationService = notificationService;
}
public async Task RegisterUserAsync(User user)
{
// Save user...
// Send welcome notification
var notification = new NotificationRequest
{
Type = NotificationType.Email,
Recipients = new[] { user.Email },
Subject = "Welcome!",
Content = "Welcome to Thaco Core platform!"
};
await _notificationService.SendNotificationAsync(notification);
}
}
Cấu hình nâng cao
Database Providers
Hỗ trợ các database providers:
- SQL Server (mặc định)
- PostgreSQL
- MySQL
- SQLite
- Oracle
{
"Query": {
"Provider": "SqlServer", // SqlServer, PostgreSQL, MySQL, SQLite, Oracle
"ConnectionString": "your-connection-string"
}
}
Message Queue Providers
{
"MessageQueue": {
"Provider": "RabbitMQ", // RabbitMQ, Redis, AzureServiceBus, AWSSQS
"ConnectionString": "amqp://guest:guest@localhost:5672/"
}
}
Cache Providers
{
"Cache": {
"UseRedis": true,
"RedisConnectionString": "localhost:6379",
"EnableMemoryCache": true
}
}
Health Checks
Package tự động đăng ký health checks cho:
- Database connectivity
- Redis connectivity
- RabbitMQ connectivity
- External APIs
Truy cập: GET /health
Metrics
Prometheus metrics được expose tại: GET /metrics
Các metrics bao gồm:
- Request duration
- Request count
- Error rate
- Cache hit/miss ratio
- Database query performance
- Message queue metrics
Logging
Sử dụng Serilog với structured logging:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
},
"File": {
"Path": "./logs/app-.log",
"RollingInterval": "Day"
}
}
}
Security Best Practices
JWT Configuration
{
"Security": {
"JWT": {
"SecretKey": "your-super-secret-key-at-least-32-characters",
"ExpirationMinutes": 60,
"RefreshTokenExpirationDays": 7
}
}
}
Rate Limiting
{
"RateLimiting": {
"EnableGlobalRateLimit": true,
"GlobalLimit": 1000,
"PerIPLimit": 100,
"PerUserLimit": 500
}
}
Performance Optimization
Database Optimization
- Connection pooling
- Query caching
- Bulk operations
- Async operations
- Retry logic
Caching Strategy
- Multi-level caching (Memory + Redis)
- Cache-aside pattern
- Write-through caching
- Cache invalidation
Response Optimization
- Response compression (Gzip, Brotli)
- Response caching
- Minimal APIs
- Async streaming
Troubleshooting
Common Issues
Database Connection Issues
- Kiểm tra connection string
- Verify database server accessibility
- Check firewall settings
Redis Connection Issues
- Verify Redis server is running
- Check Redis configuration
- Validate connection string
RabbitMQ Connection Issues
- Ensure RabbitMQ server is running
- Check credentials and virtual host
- Verify network connectivity
Email Service Issues
- Validate SMTP settings
- Check email credentials
- Verify firewall/antivirus settings
Debug Logging
Bật debug logging:
{
"Logging": {
"LogLevel": {
"MainCore.Package": "Debug"
}
}
}
Migration Guide
From Version 1.x to 2.x
- Update package reference
- Update configuration format
- Update service registration
- Test thoroughly
Contributing
- Fork the repository
- Create feature branch
- Make changes
- Add tests
- Submit pull request
License
MIT License - see LICENSE file for details.
Support
For support and questions:
- Email: support@thacocore.com
- Documentation: https://docs.thacocore.com
- Issues: https://github.com/thacocore/maincore-package/issues
Changelog
Version 1.0.0
- Initial release
- Core services implementation
- Security features
- Performance optimizations
- Monitoring and logging
- Documentation
Thaco Core Team - Building robust microservices infrastructure
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
- AspNetCore.HealthChecks.Redis (>= 9.0.0)
- AspNetCore.HealthChecks.SqlServer (>= 9.0.0)
- Autofac.Extensions.DependencyInjection (>= 10.0.0)
- AutoMapper (>= 14.0.0)
- Gridify.EntityFramework (>= 2.16.3)
- MagicOnion (>= 7.0.4)
- MagicOnion.Abstractions (>= 7.0.4)
- MagicOnion.Server (>= 7.0.4)
- MediatR (>= 12.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 8.0.15)
- Microsoft.AspNetCore.Mvc.NewtonsoftJson (>= 8.0.15)
- Microsoft.AspNetCore.Mvc.Versioning (>= 5.1.0)
- Microsoft.EntityFrameworkCore (>= 9.0.4)
- Microsoft.EntityFrameworkCore.InMemory (>= 9.0.4)
- Microsoft.EntityFrameworkCore.SqlServer (>= 9.0.4)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 9.0.5)
- Microsoft.Extensions.Http.Polly (>= 9.0.5)
- Refit (>= 8.0.0)
- Serilog.AspNetCore (>= 9.0.0)
- Serilog.Enrichers.ClientInfo (>= 2.1.2)
- Serilog.Exceptions (>= 8.4.0)
- Serilog.Extensions.Hosting (>= 9.0.0)
- Serilog.Sinks.RabbitMQ (>= 8.0.0)
- Swashbuckle.AspNetCore.Swagger (>= 8.1.1)
- Swashbuckle.AspNetCore.SwaggerGen (>= 8.1.1)
- Swashbuckle.AspNetCore.SwaggerUI (>= 8.1.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.2.8 | 101 | 6/18/2025 | |
1.2.7 | 103 | 6/18/2025 | |
1.2.6 | 107 | 6/18/2025 | |
1.2.5 | 118 | 6/16/2025 | |
1.2.4 | 279 | 6/12/2025 | |
1.2.3 | 266 | 6/10/2025 | |
1.2.2 | 258 | 6/10/2025 | |
1.2.1 | 205 | 6/9/2025 | |
1.2.0 | 197 | 6/9/2025 | |
1.1.4 | 65 | 6/7/2025 | |
1.1.3 | 60 | 6/7/2025 | |
1.1.2 | 127 | 6/6/2025 | |
1.1.1 | 134 | 5/28/2025 | |
1.1.0 | 135 | 5/28/2025 | |
1.0.3 | 142 | 5/26/2025 | |
1.0.2 | 225 | 5/26/2025 | |
1.0.1 | 229 | 5/22/2025 | |
1.0.0 | 230 | 5/22/2025 |
Initial release.