Muonroi.BuildingBlock 1.6.2

dotnet add package Muonroi.BuildingBlock --version 1.6.2
                    
NuGet\Install-Package Muonroi.BuildingBlock -Version 1.6.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="Muonroi.BuildingBlock" Version="1.6.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Muonroi.BuildingBlock" Version="1.6.2" />
                    
Directory.Packages.props
<PackageReference Include="Muonroi.BuildingBlock" />
                    
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 Muonroi.BuildingBlock --version 1.6.2
                    
#r "nuget: Muonroi.BuildingBlock, 1.6.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=Muonroi.BuildingBlock&version=1.6.2
                    
Install as a Cake Addin
#tool nuget:?package=Muonroi.BuildingBlock&version=1.6.2
                    
Install as a Cake Tool

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 with dotnet 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 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. 
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.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.9 is deprecated.
1.5.8 106 2/11/2025 1.5.8 is deprecated.
1.5.7 134 2/11/2025 1.5.7 is deprecated.
1.5.6 131 2/9/2025 1.5.6 is deprecated.
1.5.5 129 2/9/2025 1.5.5 is deprecated.
1.5.4 158 2/5/2025 1.5.4 is deprecated.
1.5.3 154 2/3/2025 1.5.3 is deprecated.
1.5.2 140 2/3/2025 1.5.2 is deprecated.
1.5.1.1 158 2/2/2025 1.5.1.1 is deprecated.
1.5.1 131 2/2/2025 1.5.1 is deprecated.
1.5.0 120 1/24/2025 1.5.0 is deprecated.
1.4.9 129 1/24/2025 1.4.9 is deprecated.
1.4.8 139 1/23/2025 1.4.8 is deprecated.
1.4.7 144 11/30/2024 1.4.7 is deprecated.
1.4.6 131 11/30/2024 1.4.6 is deprecated.
1.4.5 136 11/30/2024 1.4.5 is deprecated.
1.4.4 135 11/26/2024 1.4.4 is deprecated.
1.4.3 140 11/23/2024 1.4.3 is deprecated.
1.4.2 137 11/19/2024 1.4.2 is deprecated.
1.4.1 137 11/16/2024 1.4.1 is deprecated.
1.4.0 130 11/16/2024 1.4.0 is deprecated.
1.3.9 143 11/15/2024 1.3.9 is deprecated.
1.3.8 134 11/15/2024 1.3.8 is deprecated.
1.3.7 135 11/15/2024 1.3.7 is deprecated.
1.3.6 152 11/11/2024 1.3.6 is deprecated.
1.3.5 152 11/11/2024 1.3.5 is deprecated.
1.3.4 151 11/11/2024 1.3.4 is deprecated.
1.3.3 144 11/10/2024 1.3.3 is deprecated.
1.3.2 133 11/10/2024 1.3.2 is deprecated.
1.3.1 140 11/10/2024 1.3.1 is deprecated.
1.3.0 142 11/10/2024 1.3.0 is deprecated.
1.2.9 143 11/8/2024 1.2.9 is deprecated.
1.2.8 149 10/27/2024 1.2.8 is deprecated.
1.2.7 171 10/27/2024 1.2.7 is deprecated.
1.2.6 178 10/27/2024 1.2.6 is deprecated.
1.2.5 166 10/27/2024 1.2.5 is deprecated.
1.2.4 185 10/26/2024 1.2.4 is deprecated.
1.2.3 166 10/25/2024 1.2.3 is deprecated.
1.2.2 189 10/18/2024 1.2.2 is deprecated.
1.2.1 191 10/1/2024 1.2.1 is deprecated.
1.2.0 202 9/8/2024 1.2.0 is deprecated.
1.1.9 183 9/2/2024 1.1.9 is deprecated.
1.1.8 193 9/2/2024 1.1.8 is deprecated.
1.1.7 184 9/1/2024 1.1.7 is deprecated.
1.1.6 185 9/1/2024 1.1.6 is deprecated.
1.1.5 193 9/1/2024 1.1.5 is deprecated.
1.1.4 187 9/1/2024 1.1.4 is deprecated.
1.1.3 193 9/1/2024 1.1.3 is deprecated.
1.1.2 187 9/1/2024 1.1.2 is deprecated.
1.1.1 184 8/31/2024 1.1.1 is deprecated.
1.1.0 182 8/29/2024 1.1.0 is deprecated.
1.0.9 184 8/29/2024 1.0.9 is deprecated.
1.0.8 266 8/27/2024 1.0.8 is deprecated.
1.0.7 216 8/26/2024 1.0.7 is deprecated.
1.0.6 191 8/26/2024 1.0.6 is deprecated.
1.0.5 214 8/25/2024 1.0.5 is deprecated.
1.0.4 209 8/25/2024 1.0.4 is deprecated.
1.0.3 215 8/25/2024 1.0.3 is deprecated.
1.0.2 210 8/25/2024 1.0.2 is deprecated.
1.0.1 206 8/25/2024 1.0.1 is deprecated.
1.0.0 343 8/25/2024 1.0.0 is deprecated.

Custom error message friendly.