TGL.Backend.Core 3.1.6

There is a newer version of this package available.
See the version list below for details.
dotnet add package TGL.Backend.Core --version 3.1.6
                    
NuGet\Install-Package TGL.Backend.Core -Version 3.1.6
                    
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="TGL.Backend.Core" Version="3.1.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TGL.Backend.Core" Version="3.1.6" />
                    
Directory.Packages.props
<PackageReference Include="TGL.Backend.Core" />
                    
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 TGL.Backend.Core --version 3.1.6
                    
#r "nuget: TGL.Backend.Core, 3.1.6"
                    
#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 TGL.Backend.Core@3.1.6
                    
#: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=TGL.Backend.Core&version=3.1.6
                    
Install as a Cake Addin
#tool nuget:?package=TGL.Backend.Core&version=3.1.6
                    
Install as a Cake Tool

TGL.Backend.Core

Core backend library cho các dịch vụ .NET của TGL Solutions. Thư viện gom sẵn các building block dùng chung: multi-tenant repository, Unit of Work, xác thực PASETO / API Key, event bus trên Kafka, cache Redis, S3, logging tập trung và global exception handling — giúp khởi tạo một microservice mới nhanh và nhất quán.

NuGet .NET License


Mục lục


Cài đặt

dotnet add package TGL.Backend.Core

Hoặc thêm trực tiếp vào file .csproj:

<PackageReference Include="TGL.Backend.Core" Version="2.9.5" />

Tính năng

  • Multi-tenant repository — BaseRepository<T> tự động lọc theo SiteId (tenant) và soft-delete (IsDeleted).
  • Unit of Work — quản lý transaction, hỗ trợ nested transaction và truy xuất repository động.
  • Xác thực linh hoạt — "Smart" scheme tự chọn giữa PASETO (Bearer token) và API Key (X-API-KEY).
  • PASETO v4 — phát hành / xác thực access token (public) và refresh token (local).
  • Event Bus trên Kafka — publish/subscribe integration event, tự sinh tên topic theo môi trường.
  • Logging tập trung — Serilog + sink Kafka, enrich sẵn CorrelationId, Email, IpAddress.
  • Global exception handling — chuẩn hóa mọi lỗi về BaseResponse<T>.
  • Cache Redis — ICacheService với retry & reconnect policy.
  • S3 storage — factory + service cho AWS S3 (đa cấu hình).
  • Pagination nâng cao — filter/sort động theo dot-path, hỗ trợ navigation & collection (Any).
  • Correlation ID — middleware + delegating handler tự truyền X-Correlation-Id giữa các service.

Bắt đầu nhanh

using BackendCore.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Đăng ký toàn bộ cấu hình core (MediatR, AutoMapper, FluentValidation,
// Swagger, CORS, Auth, Kafka, JSON options...). Truyền vào 1 type bất kỳ
// nằm trong assembly ứng dụng để quét handler/validator/mapper.
builder.Services.AddServiceConfiguration<Program>(builder);

// Database + Unit of Work + Repository base
builder.Services.AddDatabaseConnection<AppDbContext>(
    Database.PostgreSQL,
    connectionString: null); // null -> đọc từ env DATABASE_CONNECTION

// Redis + S3
builder.Services.AddRedisInfrastructure(connectionString: null); // null -> env REDIS_CONNECTION

var app = builder.Build();

// Pipeline chuẩn: exception handler, swagger, cors, auth, correlation, site-key...
app.AddGlobalConfiguration();

app.Run();

Cấu hình chi tiết

Database & Unit of Work

// DbContext của bạn kế thừa BaseDbContext<T>
public class AppDbContext : BaseDbContext<AppDbContext>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
}

builder.Services.AddDatabaseConnection<AppDbContext>(Database.PostgreSQL, null);

Sử dụng Unit of Work:

public class OrderService(IUnitOfWork uow)
{
    public async Task PlaceOrderAsync(Order order)
    {
        await uow.ExecuteInTransactionAsync(async () =>
        {
            var repo = uow.EntityRepository<Order>();
            repo.Add(order);
            // SaveChanges + Commit được thực hiện tự động khi transaction kết thúc
        });
    }
}

Repository

// Cách 1: dùng repository generic mặc định
var repo = uow.EntityRepository<Order>();
var orders = await repo.FindManyAsync(o => o.Status == OrderStatus.Paid);

// Cách 2: đăng ký repository custom
builder.Services.AddRepository<Order, IOrderRepository, OrderRepository>();

BaseRepository<T> bắt buộc có AuthContext.SiteKey — mọi query đều tự lọc theo tenant và bỏ qua bản ghi đã soft-delete.

Xác thực (PASETO & API Key)

Scheme mặc định là SMART: nếu request có header X-API-KEY → dùng API Key, ngược lại → dùng PASETO.

// Phát hành access token
var accessToken = PasetoExtensions.PublishToken(new PasetoClaim
{
    UserId = user.Id,
    Email  = user.Email,
    RoleEnum = PasetoRole.User
});

// Xác thực token
var result = PasetoExtensions.VerificationToken<PasetoClaim>(accessToken);
if (result.IsSuccess) { /* result.Results chứa payload */ }

Event Bus (Kafka)

// 1. Định nghĩa event
public class OrderCreatedEvent : IntergrationEvent { public string OrderId { get; set; } }

// 2. Định nghĩa handler
public class OrderCreatedHandler : IIntegrationEventHandler<OrderCreatedEvent>
{
    public Task HandleAsync(OrderCreatedEvent @event, CancellationToken ct) { /* ... */ }
}

// 3. Đăng ký subscriber
builder.Services.SubcribeConsumer<OrderCreatedEvent, OrderCreatedHandler>();

// 4. Publish
public class OrderService(IEventBus eventBus)
{
    public Task Publish(AuthContext ctx)
        => eventBus.PublishAsync(new OrderCreatedEvent { OrderId = "..." }, ctx);
}

Tên topic tự sinh theo dạng {env}.event.{eventname} (ví dụ: prod.event.ordercreated).

Redis & S3

builder.Services.AddRedisInfrastructure(null);

public class CatalogService(ICacheService cache)
{
    public Task CacheAsync(string key, Product product)
        => cache.SetAsync(key, product, TimeSpan.FromMinutes(10));
}

AddRedisInfrastructure đồng thời đăng ký IS3Service, IS3ClientFactory, IS3ConfigProvider để làm việc với AWS S3.

Pagination nâng cao

var filter = new PaginationAdvanced
{
    PageIndex = 1,
    PageSize  = 20,
    Filters =
    [
        new FilterCriteria { Field = "status", Operator = FilterOperator.Equals, Value = "Paid" },
        new FilterCriteria { Field = "assigns.userId", Operator = FilterOperator.Equals, Value = userId }
    ],
    SortBy =
    [
        new SortCriteria { Field = "updatedAt", Direction = SortDirection.Desc }
    ]
};

var result = await repo.PaginationAdvancedAsync(filter);

Hỗ trợ dot-path cho navigation property và collection (tự sinh .Any(...)), cùng nhiều toán tử: Equals, NotEquals, In, Between, Contains, StartsWith, EndsWith, GreaterThan, LessThan, IsNull, IsNotNull, ...


Biến môi trường

Dưới đây là toàn bộ biến môi trường được thư viện đọc, nhóm theo chức năng. Cột "Bắt buộc" đánh dấu biến sẽ ném exception nếu thiếu (khi tính năng tương ứng được sử dụng).

Database & Cache

Biến Bắt buộc Mô tả
DATABASE_CONNECTION ✔¹ Chuỗi kết nối DB (PostgreSQL). Bỏ qua nếu truyền trực tiếp connection string vào AddDatabaseConnection.
REDIS_CONNECTION ✔¹ Chuỗi kết nối Redis. Bỏ qua nếu truyền trực tiếp vào AddRedisInfrastructure.

¹ Bắt buộc nếu không truyền connection string qua tham số. Ở chế độ EF Migration, DATABASE_CONNECTION có thể bỏ trống.

Tenant & Authentication

Biến Bắt buộc Mô tả
SITE_KEY ✔ Tenant key mặc định (fallback khi request không có header X-Site-Key).
API_KEY ✖ API key hợp lệ cho scheme API Key (X-API-KEY).
ODA_TOKEN ✖ Token ODA mặc định (fallback header X-Oda-Token).
TERA_CLIENT_ID ✖ Client ID cho tích hợp TERA SSO.

PASETO (Token)

Biến Bắt buộc Mô tả
PRIVATE_KEY ✔² PASETO asymmetric secret key (base64) — ký access token.
PUBLIC_KEY ✔² PASETO asymmetric public key (base64) — xác thực access token.
LOCAL_KEY ✔² PASETO symmetric key (base64) — ký/giải refresh token (Purpose.Local).

² Bắt buộc khi có sử dụng phát hành/xác thực token PASETO. Có thể sinh cặp khóa bằng PasetoExtensions.GenerateKey().

Kafka & Môi trường

Biến Bắt buộc Mô tả
KAFKA_BOOTSTRAP_SERVERS ✖ Địa chỉ Kafka broker. Có giá trị → bật event bus & Kafka log sink; trống → dùng NullEventBus.
ENVIRONMENT ✖ PRODUCTION/PROD, UAT, DEV/DEVELOPMENT/STAG/STAGGING. Ảnh hưởng tên topic, logging và cấu hình producer (idempotence khi PROD).

S3 (AWS Storage)

Biến Bắt buộc Mô tả
S3_ACCESS_KEY ✔³ Access key của S3.
S3_SECRET_KEY ✔³ Secret key của S3.
S3_BUCKET_NAME ✔³ Tên bucket mặc định.
S3_REGION ✔³ Region của S3 (ví dụ ap-southeast-1).
SETTING_SERVICE ✖ Base URL của Setting Service để lấy cấu hình S3 động (nếu có, sẽ override cấu hình từ env).

³ Bắt buộc khi sử dụng IS3Service. Nếu cấu hình SETTING_SERVICE, cấu hình S3 có thể được nạp động từ service đó.

Logging tập trung (Elasticsearch & Mattermost)

Biến Bắt buộc Mô tả
ELASTICSEARCH_CONNECTION ✔⁴ URI kết nối Elasticsearch cho consumer logging.
MATTERMOST_URL ✖ Endpoint Mattermost để gửi cảnh báo (mặc định https://chat.tgl-infra.com/api/v4/posts).
MATTERMOST_TOKEN ✔⁴ Bearer token của Mattermost.
MATTERMOST_CHANNEL_ID ✖ Channel ID nhận thông báo.
MENTIONS ✖ Danh sách user được mention khi có cảnh báo (phân tách bằng dấu phẩy).

⁴ Bắt buộc khi bật WriteLoggingService() (chạy LoggingConsumerHostedService).


Yêu cầu hệ thống

  • .NET 8.0
  • PostgreSQL (mặc định), Redis, Kafka (tùy chọn), AWS S3 (tùy chọn)

Author

  • Đặng Văn Huy — Tác giả / Maintainer
  • Công ty: TGL Solutions
  • Sản phẩm: Core Backend (TGL.Backend.Core)

License

Phát hành theo giấy phép MIT.

© TGL Solutions. All rights reserved.

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
3.2.4 134 10/12/2026
3.2.3 102 10/8/2026
3.2.2 88 10/7/2026
3.2.1 92 10/7/2026
3.2.0 109 10/5/2026
3.1.9 134 10/4/2026
3.1.8 107 10/1/2026
3.1.7 129 9/27/2026
3.1.6 124 9/17/2026
3.1.5 105 9/17/2026
3.1.4 138 9/17/2026
3.1.3 121 9/14/2026
3.1.3-preview.3 89 9/14/2026
3.1.3-preview.2 59 9/14/2026
3.1.3-preview.1 62 9/14/2026
3.1.2 97 9/11/2026
3.1.1 112 9/11/2026
3.1.0 132 9/7/2026
3.0.9-preview.2 87 8/21/2026
3.0.9-preview.1 82 8/21/2026
Loading failed