ThacoCore.Common 1.2.2

There is a newer version of this package available.
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
                    
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="ThacoCore.Common" Version="1.2.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ThacoCore.Common" Version="1.2.2" />
                    
Directory.Packages.props
<PackageReference Include="ThacoCore.Common" />
                    
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 ThacoCore.Common --version 1.2.2
                    
#r "nuget: ThacoCore.Common, 1.2.2"
                    
#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.
#addin nuget:?package=ThacoCore.Common&version=1.2.2
                    
Install ThacoCore.Common as a Cake Addin
#tool nuget:?package=ThacoCore.Common&version=1.2.2
                    
Install ThacoCore.Common as a Cake Tool

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

  1. Database Connection Issues

    • Kiểm tra connection string
    • Verify database server accessibility
    • Check firewall settings
  2. Redis Connection Issues

    • Verify Redis server is running
    • Check Redis configuration
    • Validate connection string
  3. RabbitMQ Connection Issues

    • Ensure RabbitMQ server is running
    • Check credentials and virtual host
    • Verify network connectivity
  4. 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

  1. Update package reference
  2. Update configuration format
  3. Update service registration
  4. Test thoroughly

Contributing

  1. Fork the repository
  2. Create feature branch
  3. Make changes
  4. Add tests
  5. Submit pull request

License

MIT License - see LICENSE file for details.

Support

For support and questions:

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 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. 
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
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.2 is deprecated because it is no longer maintained and has critical bugs.
1.0.1 229 5/22/2025 1.0.1 is deprecated because it is no longer maintained and has critical bugs.
1.0.0 230 5/22/2025 1.0.0 is deprecated because it is no longer maintained and has critical bugs.

Initial release.