Muonroi.BuildingBlock
1.6.2
dotnet add package Muonroi.BuildingBlock --version 1.6.2
NuGet\Install-Package Muonroi.BuildingBlock -Version 1.6.2
<PackageReference Include="Muonroi.BuildingBlock" Version="1.6.2" />
<PackageVersion Include="Muonroi.BuildingBlock" Version="1.6.2" />
<PackageReference Include="Muonroi.BuildingBlock" />
paket add Muonroi.BuildingBlock --version 1.6.2
#r "nuget: Muonroi.BuildingBlock, 1.6.2"
#addin nuget:?package=Muonroi.BuildingBlock&version=1.6.2
#tool nuget:?package=Muonroi.BuildingBlock&version=1.6.2
API Library with Dependency Injection and Serilog Configuration
Introduction
This library provides entities such as User
, Role
, Permission
, and Language
, and comes with built-in Dependency Injection features, Bearer Token management, JSON handling utilities, string conversion, and localization for multiple languages.
Prerequisites
- .NET SDK 8.0 or higher must be installed. You can download it from the official website.
- Build the project with
dotnet build
and create a NuGet package withdotnet pack
.
See the Samples/Program.cs
file for a minimal setup example.
Usage Guide
1. Configuring Program.cs
Here's how to configure your Program.cs
file:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
Assembly assembly = Assembly.GetExecutingAssembly();
ConfigurationManager configuration = builder.Configuration;
builder.AddAppConfiguration();
builder.AddAutofacConfiguration();
builder.Host.UseSerilog((context, services, loggerConfiguration) =>
{
MSerilogAction.Configure(context, services, loggerConfiguration, false);
});
Log.Information("Starting {ApplicationName} API up", builder.Environment.ApplicationName);
try
{
IServiceCollection services = builder.Services;
// Register services
services.AddApplication(assembly);
services.AddInfrastructure<Program>(configuration);
services.SwaggerConfig(builder.Environment.ApplicationName);
services.AddScopeServices(typeof(<Your Db context>).Assembly);
services.AddValidateBearerToken<MTokenInfo, <Your Enum permission>>(configuration);
services.AddDbContextConfigure<<Your Db context>, <Your Enum permission>>(configuration);
services.AddCors(configuration);
services.AddPermissionFilter<<Your Enum permission>>();
services.ConfigureMapper();
WebApplication app = builder.Build();
app.UseCors("MAllowDomains");
app.UseDefaultMiddleware<<Your Db context>, <Your Enum permission>>();
app.AddLocalization(assembly);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.ConfigureEndpoints();
app.MigrateDatabase<<Your Db context>>();
await app.RunAsync();
}
catch (Exception ex)
{
Log.Fatal(ex, "Unhandled exception: {Message}", ex.Message);
}
finally
{
Log.Information("Shut down {ApplicationName} complete", builder.Environment.ApplicationName);
await Log.CloseAndFlushAsync();
}
2. Example appsettings.json
Configuration
Here's an example of the appsettings.json
configuration that can be used with this library:
{
"DatabaseConfigs": {
"DbType": "Sqlite",
"ConnectionStrings": {
"SqliteConnectionString": "Your encrypt connection string by serect key",
"MongoDbConnectionString": "Your encrypt connection string by serect key",
"SqlServerConnectionString": "Your encrypt connection string by serect key",
"MySqlConnectionString": "Your encrypt connection string by serect key",
"PostgreSqlConnectionString": "Your encrypt connection string by serect key"
}
},
"ApiKey": "",
"CacheConfigs": {
"CacheType": "MultiLevel" // Memory | Redis | MultiLevel
// Choose caching strategy
},
"RedisConfigs": {
"Enable": true,
"Host": "Your encrypt by serect key",
"Port": "Your encrypt by serect key",
"Password": "Your encrypt by serect key",
"Expire": 30,
"KeyPrefix": "Your encrypt by serect key",
"AllMethodsEnableCache": false
},
"TokenConfigs": {
"Issuer": "https://exampledomain.com",
"Audience": "https://searchpartners.exampledomain.com",
"SigningKeys": "",
"ExpiryMinutes": 30,
"PublicKey": "-----BEGIN PUBLIC KEY-----\n-----END PUBLIC KEY-----",
"PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\n-----END RSA PRIVATE KEY-----"
},
"PaginationConfigs": {
"DefaultPageIndex": 1,
"DefaultPageSize": 10,
"MaxPageSize": 10
},
"ResourceSetting": {
"ResourceName": "Resources.ErrorMessages",
"lang": "vi-VN"
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Elastic.Serilog.Sinks" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning",
"System": "Warning"
}
},
"MAllowDomains": "https://localhost:52182,http://localhost:4200",
"GrpcServices": {
"Services": {
"Your service 1": { "Uri": "Your service url" },
"Your service 2": { "Uri": "Your service url" },
"Your service 3": { "Uri": "Your service url" }
}
},
"ConsulConfigs": {
"ServiceName": "MyService",
"ConsulAddress": "Your service url",
"ServiceAddress": "http://localhost",
"ServicePort": 5000,
"ServiceMetadata": {
"version": "1.0.0",
"environment": "production"
}
},
"MessageBusConfigs": {
"BusType": "RabbitMq",
"RabbitMq": {
"Host": "localhost",
"VirtualHost": "/",
"Username": "guest",
"Password": "guest"
},
"Kafka": {
"Host": "localhost:9092",
"Topic": "sample-topic",
"GroupId": "sample-group"
}
},
"BackgroundJobConfigs": {
"JobType": "Hangfire",
"ConnectionString": "Your job storage connection string"
},
"KubernetesConfigs": {
"ClusterType": "K8s",
"ClusterEndpoint": "https://your-cluster-api"
},
"ApiKey": "Your api key use with grpc",
"SecretKey": "Your serect key use encrypt impotant value",
"EnableEncryption": true,
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "Elasticsearch",
"Args": {
"bootstrapMethod": "Silent",
"nodes": [ "http://localhost:9200" ],
"dataStream": "logs-muonroi-default",
"ilmPolicy": "muonroi-policy"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Notifications"
}
},
"ErrorInAverageEveryNTime": 2,
"WarningInAverageEveryNTime": 2
}
To use the new helper for Elasticsearch logging, add a separate section:
"Serilog:Elasticsearch": {
"bootstrapMethod": "Silent",
"nodes": [ "http://localhost:9200" ],
"dataStream": "logs-muonroi-default",
"ilmPolicy": "muonroi-policy"
}
3. Providing Resource Files
Create a Resources
directory in your project and place localization JSON files inside it. Each file should follow the pattern ErrorMessages-<culture>.json
and contain key/value pairs of error codes and messages. For example, Resources/ErrorMessages-en-US.json
would hold English messages. Ensure that the ResourceSetting.ResourceName
value (as shown above) matches the base file name without the culture suffix so the library can load the correct file based on the configured lang
.
Main Components
1. Entities
- User: Manages users.
- Role: Manages user roles.
- Permission: Manages access permissions.
- Language: Manages languages.
2. Dependency Injection
- Integrates necessary services via Dependency Injection (DI) to manage the application lifecycle.
3. Bearer Token
- Manages Bearer Token, authentication, and authorization.
4. JSON Utilities
- Provides utilities for handling JSON, such as converting between strings and objects.
5. Localization
- Supports language localization within the application for various languages.
6. Cryptography
MCryptographyExtension
now uses SHA-256 hashing in place of MD5 for improved security.
7. Background Jobs
- Provides configuration for background job schedulers like Hangfire or Quartz.
Redis Caching
Use CacheConfigs
to select a caching strategy and specify RedisConfigs
when using Redis or multi-level caching.
"CacheConfigs": {
"CacheType": "MultiLevel"
},
"RedisConfigs": {
"Enable": true,
"Host": "localhost",
"Port": "6379",
"Password": "",
"Expire": 30,
"KeyPrefix": "app"
}
services.AddMultiLevelCaching(configuration);
gRPC Integration
Use the helpers in External/Grpc
to configure gRPC servers and clients.
The GrpcHandler
class exposes extension methods for registering gRPC services and clients based on settings in appsettings.json
.
Consul Integration
Service discovery support is provided in External/Consul
.
The ConsulHandler
class registers your service with Consul during startup and removes it on shutdown.
An asynchronous version UseServiceDiscoveryAsync
is available to avoid blocking calls during startup.
Message Bus Integration
Configure Kafka or RabbitMQ brokers easily using MassTransit. The helper in External/Messaging
selects the broker based on MessageBusConfigs
in your configuration file.
Register consumers by calling services.AddMessageBus(configuration, Assembly.GetExecutingAssembly(), cfg => { /* Saga config */ });
in your startup.
Use PublishWithAuthContext
on IPublishEndpoint
to automatically include authentication headers when sending messages.
Kafka Example
"MessageBusConfigs": {
"BusType": "Kafka",
"Kafka": {
"Host": "localhost:9092",
"Topic": "sample-topic",
"GroupId": "sample-group"
}
}
services.AddMessageBus(configuration, Assembly.GetExecutingAssembly());
Background Job Configuration
Configure background jobs using the BackgroundJobConfigs
section. Choose Hangfire
or Quartz
and specify a connection string for job storage.
"BackgroundJobConfigs": {
"JobType": "Hangfire",
"ConnectionString": "Server=mydb;Database=jobs;User Id=sa;Password=your_password;"
}
services.AddHangfire(x => x.UseSqlServerStorage(configuration["BackgroundJobConfigs:ConnectionString"]));
app.UseHangfireDashboard();
Enqueue jobs with:
BackgroundJob.Enqueue(() => Console.WriteLine("Hello from Hangfire"));
Kubernetes Integration
Deployment details for k8s
or k3s
clusters can be specified under KubernetesConfigs
. This includes the cluster type and the API endpoint.
Gateway Configuration
See docs/gateway-guide.md for instructions on running the service behind Kong or Azure API Management gateways.
Contribution
Please submit pull requests or open issues on GitHub to contribute or report bugs for this project.
Formatting
Run dotnet format Muonroi.BuildingBlock.sln
to apply the coding style defined in .editorconfig
.
Documentation
This project uses DocFX to generate the documentation. See docs/docfx-huong-dan.md for configuration and usage instructions. See docs/permission-guide.md for details on the authorization system and default tables.
License
This library is licensed under the MIT License. Please see the LICENSE
file for more details.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. 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. |
-
net9.0
- Asp.Versioning.Mvc (>= 8.1.0)
- Autofac (>= 8.3.0)
- Autofac.Extensions.DependencyInjection (>= 10.0.0)
- AutoMapper (>= 14.0.0)
- Azure.Core (>= 1.46.2)
- Azure.Identity (>= 1.14.0)
- BCrypt.Net-Core (>= 1.6.0)
- BouncyCastle.NetCore (>= 2.2.1)
- Castle.Core (>= 5.2.1)
- Consul (>= 1.7.14.7)
- Dapper (>= 2.1.66)
- Dapper.Extensions.Caching.Redis (>= 5.3.1)
- Dapper.Extensions.MSSQL (>= 5.3.1)
- Dapper.Extensions.MySQL (>= 5.3.1)
- Dapper.Extensions.NetCore (>= 5.3.1)
- Dapper.Extensions.PostgreSQL (>= 5.3.1)
- DnsClient (>= 1.8.0)
- Elastic.Serilog.Sinks (>= 8.18.1)
- FluentValidation (>= 12.0.0)
- FluentValidation.AspNetCore (>= 11.3.1)
- FluentValidation.DependencyInjectionExtensions (>= 12.0.0)
- FreeRedis (>= 1.4.0)
- Google.Protobuf (>= 3.31.1)
- Grpc.AspNetCore.Server (>= 2.71.0)
- Grpc.Core.Api (>= 2.71.0)
- Grpc.Net.Client (>= 2.71.0)
- Grpc.Net.ClientFactory (>= 2.71.0)
- Grpc.Net.Common (>= 2.71.0)
- JetBrains.Annotations (>= 2024.3.0)
- MassTransit (>= 8.4.1)
- MassTransit.Kafka (>= 8.4.1)
- MassTransit.RabbitMQ (>= 8.4.1)
- MediatR (>= 12.5.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 9.0.5)
- Microsoft.AspNetCore.Identity.EntityFrameworkCore (>= 9.0.5)
- Microsoft.AspNetCore.OpenApi (>= 9.0.5)
- Microsoft.Bcl.AsyncInterfaces (>= 9.0.5)
- Microsoft.Bcl.Cryptography (>= 9.0.5)
- Microsoft.Data.SqlClient (>= 6.0.2)
- Microsoft.Data.SqlClient.SNI.runtime (>= 6.0.2)
- Microsoft.Data.Sqlite.Core (>= 9.0.5)
- Microsoft.EntityFrameworkCore (>= 9.0.5)
- Microsoft.EntityFrameworkCore.Abstractions (>= 9.0.5)
- Microsoft.EntityFrameworkCore.Analyzers (>= 9.0.5)
- Microsoft.EntityFrameworkCore.InMemory (>= 9.0.5)
- Microsoft.EntityFrameworkCore.Relational (>= 9.0.5)
- Microsoft.EntityFrameworkCore.Sqlite (>= 9.0.5)
- Microsoft.EntityFrameworkCore.Sqlite.Core (>= 9.0.5)
- Microsoft.EntityFrameworkCore.SqlServer (>= 9.0.5)
- Microsoft.Extensions.Caching.Abstractions (>= 9.0.5)
- Microsoft.Extensions.Caching.Memory (>= 9.0.5)
- Microsoft.Extensions.Caching.StackExchangeRedis (>= 9.0.5)
- Microsoft.Extensions.Configuration (>= 9.0.5)
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.5)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.5)
- Microsoft.Extensions.Configuration.EnvironmentVariables (>= 9.0.5)
- Microsoft.Extensions.Configuration.FileExtensions (>= 9.0.5)
- Microsoft.Extensions.Configuration.Json (>= 9.0.5)
- Microsoft.Extensions.DependencyInjection (>= 9.0.5)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.5)
- Microsoft.Extensions.DependencyModel (>= 9.0.5)
- Microsoft.Extensions.FileProviders.Abstractions (>= 9.0.5)
- Microsoft.Extensions.FileProviders.Physical (>= 9.0.5)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.5)
- Microsoft.Extensions.Http (>= 9.0.5)
- Microsoft.Extensions.Http.Diagnostics (>= 9.5.0)
- Microsoft.Extensions.Http.Resilience (>= 9.5.0)
- Microsoft.Extensions.Identity.Stores (>= 9.0.5)
- Microsoft.Extensions.Logging (>= 9.0.5)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.5)
- Microsoft.Extensions.ObjectPool (>= 9.0.5)
- Microsoft.Extensions.Options (>= 9.0.5)
- Microsoft.Extensions.Primitives (>= 9.0.5)
- Microsoft.Extensions.Resilience (>= 9.5.0)
- Microsoft.Identity.Client (>= 4.72.1)
- Microsoft.Identity.Client.Extensions.Msal (>= 4.72.1)
- Microsoft.IdentityModel.Abstractions (>= 8.12.0)
- Microsoft.IdentityModel.JsonWebTokens (>= 8.12.0)
- Microsoft.IdentityModel.Logging (>= 8.12.0)
- Microsoft.IdentityModel.Protocols.OpenIdConnect (>= 8.12.0)
- Microsoft.IdentityModel.Tokens (>= 8.12.0)
- Microsoft.OpenApi (>= 1.6.24)
- MongoDB.Bson (>= 3.4.0)
- MongoDB.Driver (>= 3.4.0)
- MySql.Data (>= 9.3.0)
- MySql.EntityFrameworkCore (>= 9.0.3)
- MySqlConnector (>= 2.4.0)
- NetJSON (>= 1.4.4)
- Npgsql (>= 9.0.3)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 9.0.4)
- Polly (>= 8.5.2)
- Polly.Core (>= 8.5.2)
- Polly.Extensions.Http (>= 3.0.0)
- Pomelo.EntityFrameworkCore.MySql (>= 9.0.0-preview.3.efcore.9.0.0)
- RestEase (>= 1.6.4)
- Serilog (>= 4.3.0)
- Serilog.AspNetCore (>= 9.0.0)
- Serilog.Enrichers.Environment (>= 3.0.1)
- Serilog.Enrichers.Process (>= 3.0.0)
- Serilog.Enrichers.Thread (>= 4.0.0)
- Serilog.Exceptions (>= 8.4.0)
- Serilog.Expressions (>= 5.0.0)
- Serilog.Extensions.Hosting (>= 9.0.0)
- Serilog.Formatting.Compact (>= 3.0.0)
- Serilog.Formatting.Elasticsearch (>= 10.0.0)
- Serilog.Settings.Configuration (>= 9.0.0)
- Serilog.Sinks.Console (>= 6.0.0)
- Serilog.Sinks.Debug (>= 3.0.0)
- Serilog.Sinks.File (>= 7.0.0)
- SharpCompress (>= 0.40.0)
- Snappier (>= 1.2.0)
- SQLitePCLRaw.bundle_e_sqlite3 (>= 2.1.11)
- SQLitePCLRaw.core (>= 2.1.11)
- StackExchange.Redis (>= 2.8.37)
- Swashbuckle.AspNetCore (>= 8.1.4)
- Swashbuckle.AspNetCore.Swagger (>= 8.1.4)
- Swashbuckle.AspNetCore.SwaggerGen (>= 8.1.4)
- Swashbuckle.AspNetCore.SwaggerUI (>= 8.1.4)
- System.Buffers (>= 4.6.1)
- System.Configuration.ConfigurationManager (>= 9.0.5)
- System.Data.SqlClient (>= 4.9.0)
- System.Diagnostics.DiagnosticSource (>= 9.0.5)
- System.Diagnostics.EventLog (>= 9.0.5)
- System.IdentityModel.Tokens.Jwt (>= 8.12.0)
- System.Linq.Async (>= 6.0.1)
- System.Memory (>= 4.6.3)
- System.Reflection.Emit (>= 4.7.0)
- System.Reflection.Emit.ILGeneration (>= 4.7.0)
- System.Reflection.Emit.Lightweight (>= 4.7.0)
- System.Security.Cryptography.Pkcs (>= 9.0.5)
- System.Text.Json (>= 9.0.5)
- System.Threading.Tasks.Extensions (>= 4.6.3)
- ZstdSharp.Port (>= 0.8.5)
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.6.2 | 77 | 6/22/2025 | |
1.6.1 | 266 | 6/10/2025 | |
1.6.0 | 68 | 6/7/2025 | |
1.5.11 | 181 | 4/29/2025 | |
1.5.10 | 196 | 4/17/2025 | |
1.5.9.9 | 216 | 3/31/2025 | |
1.5.9.8 | 473 | 3/25/2025 | |
1.5.9.7 | 164 | 3/17/2025 | |
1.5.9.6 | 152 | 3/13/2025 | |
1.5.9.5 | 154 | 3/9/2025 | |
1.5.9.4 | 226 | 3/6/2025 | |
1.5.9.3 | 221 | 3/5/2025 | |
1.5.9.2 | 110 | 2/23/2025 | |
1.5.9.1 | 172 | 2/18/2025 | |
1.5.9 | 109 | 2/17/2025 | |
1.5.8 | 106 | 2/11/2025 | |
1.5.7 | 134 | 2/11/2025 | |
1.5.6 | 131 | 2/9/2025 | |
1.5.5 | 129 | 2/9/2025 | |
1.5.4 | 158 | 2/5/2025 | |
1.5.3 | 154 | 2/3/2025 | |
1.5.2 | 140 | 2/3/2025 | |
1.5.1.1 | 158 | 2/2/2025 | |
1.5.1 | 131 | 2/2/2025 | |
1.5.0 | 120 | 1/24/2025 | |
1.4.9 | 129 | 1/24/2025 | |
1.4.8 | 139 | 1/23/2025 | |
1.4.7 | 144 | 11/30/2024 | |
1.4.6 | 131 | 11/30/2024 | |
1.4.5 | 136 | 11/30/2024 | |
1.4.4 | 135 | 11/26/2024 | |
1.4.3 | 140 | 11/23/2024 | |
1.4.2 | 137 | 11/19/2024 | |
1.4.1 | 137 | 11/16/2024 | |
1.4.0 | 130 | 11/16/2024 | |
1.3.9 | 143 | 11/15/2024 | |
1.3.8 | 134 | 11/15/2024 | |
1.3.7 | 135 | 11/15/2024 | |
1.3.6 | 152 | 11/11/2024 | |
1.3.5 | 152 | 11/11/2024 | |
1.3.4 | 151 | 11/11/2024 | |
1.3.3 | 144 | 11/10/2024 | |
1.3.2 | 133 | 11/10/2024 | |
1.3.1 | 140 | 11/10/2024 | |
1.3.0 | 142 | 11/10/2024 | |
1.2.9 | 143 | 11/8/2024 | |
1.2.8 | 149 | 10/27/2024 | |
1.2.7 | 171 | 10/27/2024 | |
1.2.6 | 178 | 10/27/2024 | |
1.2.5 | 166 | 10/27/2024 | |
1.2.4 | 185 | 10/26/2024 | |
1.2.3 | 166 | 10/25/2024 | |
1.2.2 | 189 | 10/18/2024 | |
1.2.1 | 191 | 10/1/2024 | |
1.2.0 | 202 | 9/8/2024 | |
1.1.9 | 183 | 9/2/2024 | |
1.1.8 | 193 | 9/2/2024 | |
1.1.7 | 184 | 9/1/2024 | |
1.1.6 | 185 | 9/1/2024 | |
1.1.5 | 193 | 9/1/2024 | |
1.1.4 | 187 | 9/1/2024 | |
1.1.3 | 193 | 9/1/2024 | |
1.1.2 | 187 | 9/1/2024 | |
1.1.1 | 184 | 8/31/2024 | |
1.1.0 | 182 | 8/29/2024 | |
1.0.9 | 184 | 8/29/2024 | |
1.0.8 | 266 | 8/27/2024 | |
1.0.7 | 216 | 8/26/2024 | |
1.0.6 | 191 | 8/26/2024 | |
1.0.5 | 214 | 8/25/2024 | |
1.0.4 | 209 | 8/25/2024 | |
1.0.3 | 215 | 8/25/2024 | |
1.0.2 | 210 | 8/25/2024 | |
1.0.1 | 206 | 8/25/2024 | |
1.0.0 | 343 | 8/25/2024 |
Custom error message friendly.