Muonroi.BuildingBlock 1.6.7

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

Muonroi Building Block

Ask DeepWiki

Introduction

This library provides entities such as User, Role, Permission, and Language, along with built-in dependency injection, bearer token management, JSON handling utilities, string conversion, and localization for multiple languages. It now also includes a lightweight rule engine that supports strongly typed rules and dynamic JSON workflows. The package is designed to accelerate the development of .NET applications following a clean architecture.

Prerequisites

  • .NET SDK 9.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.

Quick Start

You can also use the muonroibase.template dotnet template:

dotnet new install muonroibase.template
dotnet new muonroibase -n YourNewProjectName -C MyCoreName

See the Samples/Program.cs file for a minimal setup example. Additional samples are provided in the Samples folder:

  • MemoryCache demonstrates basic in-memory caching.
  • MultiLevelCache shows how to combine memory and distributed caches.
  • RedisCache illustrates using Redis as a distributed cache.
  • MultipleCache demonstrates using both IMemoryCache and IMultiLevelCacheService.
  • HelloRules highlights the built-in rule engine.
  • ImportExportRules shows versioned JSON workflows.
  • PaymentApproval orchestrates multiple rules for a business scenario.

Usage Guide

1. Configuring Program.cs

Here's how to configure your Program.cs file to use the library's features:

using System.Reflection;
using Muonroi.BuildingBlock.External;
using Muonroi.BuildingBlock.External.Common.Constants;
using Muonroi.BuildingBlock.External.Cors;
using Muonroi.BuildingBlock.External.DI;
using Muonroi.BuildingBlock.External.Entity;
using Muonroi.BuildingBlock.External.Entity.DataSample;
using Muonroi.BuildingBlock.External.Logging;
using Muonroi.BuildingBlock.External.Messaging;
using Muonroi.BuildingBlock.External.Caching.Distributed.MultiLevel;
using Muonroi.BuildingBlock.External.Grpc;
using Muonroi.BuildingBlock.External.Consul;
using Serilog;
// Replace with your project's using statements
// using YourProject.Data; 
// using YourProject.Permissions;

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(configuration);
    services.SwaggerConfig(builder.Environment.ApplicationName);
    services.AddScopeServices(typeof(<YourDbContext>).Assembly);
    services.AddValidateBearerToken<<YourDbContext>, MTokenInfo, <YourPermissionEnum>>(configuration);
    services.AddDbContextConfigure<<YourDbContext>, <YourPermissionEnum>>(configuration);
    services.AddCors(configuration);
    services.AddPermissionFilter<<YourPermissionEnum>>();
    services.ConfigureMapper();

    // Optional Integrations
    services.AddMultiLevelCaching(configuration);
    services.AddMessageBus(configuration, assembly);
    services.AddGrpcServer();
    services.AddServiceDiscovery(configuration, builder.Environment);
    services.AddObservability(configuration);

    WebApplication app = builder.Build();
    
    await app.UseServiceDiscoveryAsync(builder.Environment);
    app.UseCors("MAllowDomains");
    app.UseDefaultMiddleware<<YourDbContext>, <YourPermissionEnum>>();
    app.AddLocalization(assembly);
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.ConfigureEndpoints();
    app.MigrateDatabase<<YourDbContext>>();

    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 a comprehensive example of the appsettings.json configuration:

{
  "DatabaseConfigs": {
    "DbType": "Sqlite",
    "ConnectionStrings": {
      "SqliteConnectionString": "Your encrypted connection string by secret key",
      "MongoDbConnectionString": "Your encrypted connection string by secret key",
      "SqlServerConnectionString": "Your encrypted connection string by secret key",
      "MySqlConnectionString": "Your encrypted connection string by secret key",
      "PostgreSqlConnectionString": "Your encrypted connection string by secret key"
    }
  },
  "ApiKey": "",
  "CacheConfigs": {
    "CacheType": "MultiLevel"
  },
  "RedisConfigs": {
    "Enable": true,
    "Host": "Your host encrypted by secret key",
    "Port": "Your port encrypted by secret key",
    "Password": "Your password encrypted by secret key",
    "Expire": 30,
    "KeyPrefix": "Your prefix encrypted by secret key",
    "AllMethodsEnableCache": false
  },
  "TokenConfigs": {
    "Issuer": "https://exampledomain.com",
    "Audience": "https://searchpartners.exampledomain.com",
    "SigningKeys": "",
    "UseRsa": true,
    "ExpiryMinutes": 30,
    "EnableCookieAuth": true,
    "CookieName": "AuthToken",
    "CookieSameSite": "Lax",
    "PublicKey": "-----BEGIN PUBLIC KEY-----\n...-----END PUBLIC KEY-----",
    "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\n...-----END RSA PRIVATE KEY-----"
  },
  "PaginationConfigs": {
    "DefaultPageIndex": 1,
    "DefaultPageSize": 10,
    "MaxPageSize": 100
  },
  "ResourceSetting": {
    "ResourceName": "Resources.ErrorMessages",
    "lang": "vi-VN"
  },
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Elastic.Serilog.Sinks" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft.AspNetCore": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "logs/log-.json", "formatter": "Serilog.Formatting.Elasticsearch.ElasticsearchJsonFormatter, Serilog.Formatting.Elasticsearch" }
      },
      {
        "Name": "Elasticsearch",
        "Args": {
          "bootstrapMethod": "Silent",
          "nodes": [ "http://localhost:9200" ],
          "dataStream": "logs-muonroi-default",
          "ilmPolicy": "muonroi-policy"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "MyApplication"
    }
  },
  "MAllowDomains": "https://localhost:52182,http://localhost:4200",
  "GrpcServices": {
    "Services": {
      "YourService1": { "Uri": "http://localhost:5001" },
      "YourService2": { "Uri": "http://localhost:5002" }
    }
  },
  "ConsulConfigs": {
    "ServiceName": "MyService",
    "ConsulAddress": "http://localhost:8500",
    "ServiceAddress": "http://localhost",
    "ServicePort": 5000
  },
  "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"
  },
  "OpenTelemetry": {
    "ServiceName": "MyService",
    "OtlpEndpoint": "http://localhost:4317"
  },
  "SecretKey": "Your secret key used to encrypt important values",
  "EnableEncryption": true
}

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 (e.g., ErrorMessages-en-US.json) and contain key-value pairs of error codes and messages. Ensure the ResourceSetting.ResourceName value in appsettings.json matches the base file name.

Main Components

  • Entities: Core data models like MUser, MRole, MPermission, and MLanguage.
  • Dependency Injection: Pre-configured DI using Autofac for managing application services and lifecycles.
  • Authentication & Authorization: Robust token-based security with JWT, refresh tokens, and a flexible permission system.
  • Data Access: Generic repositories (MRepository<T>) and query classes (MQuery<T>) for Entity Framework Core, along with Dapper integration for performance-critical queries.
  • Caching: Multi-level caching support (in-memory and Redis) to improve performance.
  • Rule Engine: Compose strongly typed IRule<T> classes and dynamic JSON workflows with dependency ordering and feature toggles.
  • Service Discovery: Consul integration for registering and discovering services in a microservices environment.
  • Message Bus: MassTransit integration for both RabbitMQ and Kafka to enable asynchronous communication and Saga patterns.
  • Background Jobs: Configuration helpers for background job schedulers like Hangfire or Quartz.
  • gRPC: Helpers to easily configure gRPC servers and clients.
  • Logging: Centralized logging with Serilog, including out-of-the-box support for Elasticsearch.
  • Cryptography: MCryptographyExtension uses SHA-256 for secure hashing and AES for configuration encryption.
  • Localization: Built-in support for multiple languages using JSON resource files.

Rule Engine

The Muonroi.RuleEngine packages provide a flexible way to evaluate business rules. Rules implement IRule<T> and can declare dependencies, hook points, and optional feature flags. JSON workflows can be loaded at runtime through RulesEngineService, and results are collected in a FactBag for later rules.

services.AddRuleEngine().AddRulesFromAssemblies(typeof(Program).Assembly);

For practical examples see the HelloRules, ImportExportRules, and PaymentApproval samples or read the Rule Engine Guide.

Integrations

Redis Caching

Configure caching via CacheConfigs and RedisConfigs in your settings.

// In Program.cs
services.AddMultiLevelCaching(configuration);

gRPC Integration

Use helpers in External/Grpc to configure gRPC. The GrpcHandler class provides extension methods for registering servers and clients from appsettings.json.

Consul Integration

Service discovery support is provided in External/Consul. The ConsulHandler registers and deregisters your service with Consul automatically. Call AddServiceDiscovery and UseServiceDiscoveryAsync in Program.cs.

Message Bus (Kafka/RabbitMQ)

Configure your message broker via MessageBusConfigs. The helper in External/Messaging uses MassTransit to select the broker. Register consumers and sagas easily:

// In Program.cs
services.AddMessageBus(configuration, Assembly.GetExecutingAssembly(), cfg => { 
    /* Optional Saga/Consumer configuration */ 
});

Use PublishWithAuthContext on IPublishEndpoint to automatically include authentication headers when publishing messages.

Background Job Configuration

Configure background jobs using the BackgroundJobConfigs section. Choose Hangfire or Quartz and specify a connection string for job storage.

// Example for Hangfire with SQL Server
services.AddHangfire(x => x.UseSqlServerStorage(configuration["BackgroundJobConfigs:ConnectionString"]));
app.UseHangfireDashboard();
BackgroundJob.Enqueue(() => Console.WriteLine("Hello from Hangfire"));

Kubernetes Integration

Specify deployment details for k8s or k3s clusters under KubernetesConfigs, including the cluster type and API endpoint.

Documentation

This project uses DocFX to generate documentation.

  • To build the documentation, run: docfx build
  • To preview the documentation locally, run: docfx serve _site

For more details, see the guides in the docs directory:

ASVS Pre-Merge Checklist

  • Security Configuration (V14) – verify secure configuration and secret management.
  • Input Validation (V5) – validate and sanitize all inputs.
  • Authorization (V4) – enforce RBAC and deny by default.

For a detailed checklist see docs/asvs-checklist.md.

Formatting

Run dotnet format Muonroi.BuildingBlock.sln to apply the coding style defined in .editorconfig.

Contribution

Please submit pull requests or open issues on GitHub to contribute or report bugs for this project.

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.7.1 11 8/17/2025
1.6.7 13 8/17/2025
1.6.6 11 8/17/2025
1.6.5 102 7/27/2025
1.6.4 485 7/23/2025
1.6.3 184 7/20/2025
1.6.2 92 6/22/2025
1.6.1 276 6/10/2025
1.6.0 81 6/7/2025
1.5.11 192 4/29/2025
1.5.10 201 4/17/2025
1.5.9.9 223 3/31/2025
1.5.9.8 478 3/25/2025
1.5.9.7 175 3/17/2025
1.5.9.6 158 3/13/2025
1.5.9.5 160 3/9/2025
1.5.9.4 232 3/6/2025
1.5.9.3 228 3/5/2025
1.5.9.2 118 2/23/2025
1.5.9.1 190 2/18/2025
1.5.9 122 2/17/2025 1.5.9 is deprecated.
1.5.8 121 2/11/2025 1.5.8 is deprecated.
1.5.7 143 2/11/2025 1.5.7 is deprecated.
1.5.6 140 2/9/2025 1.5.6 is deprecated.
1.5.5 145 2/9/2025 1.5.5 is deprecated.
1.5.4 169 2/5/2025 1.5.4 is deprecated.
1.5.3 167 2/3/2025 1.5.3 is deprecated.
1.5.2 154 2/3/2025 1.5.2 is deprecated.
1.5.1.1 172 2/2/2025 1.5.1.1 is deprecated.
1.5.1 142 2/2/2025 1.5.1 is deprecated.
1.5.0 137 1/24/2025 1.5.0 is deprecated.
1.4.9 143 1/24/2025 1.4.9 is deprecated.
1.4.8 148 1/23/2025 1.4.8 is deprecated.
1.4.7 155 11/30/2024 1.4.7 is deprecated.
1.4.6 141 11/30/2024 1.4.6 is deprecated.
1.4.5 149 11/30/2024 1.4.5 is deprecated.
1.4.4 145 11/26/2024 1.4.4 is deprecated.
1.4.3 157 11/23/2024 1.4.3 is deprecated.
1.4.2 146 11/19/2024 1.4.2 is deprecated.
1.4.1 148 11/16/2024 1.4.1 is deprecated.
1.4.0 140 11/16/2024 1.4.0 is deprecated.
1.3.9 152 11/15/2024 1.3.9 is deprecated.
1.3.8 149 11/15/2024 1.3.8 is deprecated.
1.3.7 148 11/15/2024 1.3.7 is deprecated.
1.3.6 160 11/11/2024 1.3.6 is deprecated.
1.3.5 163 11/11/2024 1.3.5 is deprecated.
1.3.4 161 11/11/2024 1.3.4 is deprecated.
1.3.3 157 11/10/2024 1.3.3 is deprecated.
1.3.2 145 11/10/2024 1.3.2 is deprecated.
1.3.1 152 11/10/2024 1.3.1 is deprecated.
1.3.0 155 11/10/2024 1.3.0 is deprecated.
1.2.9 155 11/8/2024 1.2.9 is deprecated.
1.2.8 162 10/27/2024 1.2.8 is deprecated.
1.2.7 186 10/27/2024 1.2.7 is deprecated.
1.2.6 198 10/27/2024 1.2.6 is deprecated.
1.2.5 185 10/27/2024 1.2.5 is deprecated.
1.2.4 207 10/26/2024 1.2.4 is deprecated.
1.2.3 189 10/25/2024 1.2.3 is deprecated.
1.2.2 205 10/18/2024 1.2.2 is deprecated.
1.2.1 214 10/1/2024 1.2.1 is deprecated.
1.2.0 221 9/8/2024 1.2.0 is deprecated.
1.1.9 202 9/2/2024 1.1.9 is deprecated.
1.1.8 208 9/2/2024 1.1.8 is deprecated.
1.1.7 200 9/1/2024 1.1.7 is deprecated.
1.1.6 201 9/1/2024 1.1.6 is deprecated.
1.1.5 210 9/1/2024 1.1.5 is deprecated.
1.1.4 209 9/1/2024 1.1.4 is deprecated.
1.1.3 212 9/1/2024 1.1.3 is deprecated.
1.1.2 206 9/1/2024 1.1.2 is deprecated.
1.1.1 202 8/31/2024 1.1.1 is deprecated.
1.1.0 199 8/29/2024 1.1.0 is deprecated.
1.0.9 203 8/29/2024 1.0.9 is deprecated.
1.0.8 282 8/27/2024 1.0.8 is deprecated.
1.0.7 240 8/26/2024 1.0.7 is deprecated.
1.0.6 212 8/26/2024 1.0.6 is deprecated.
1.0.5 233 8/25/2024 1.0.5 is deprecated.
1.0.4 227 8/25/2024 1.0.4 is deprecated.
1.0.3 236 8/25/2024 1.0.3 is deprecated.
1.0.2 226 8/25/2024 1.0.2 is deprecated.
1.0.1 223 8/25/2024 1.0.1 is deprecated.
1.0.0 374 8/25/2024 1.0.0 is deprecated.

Custom error message friendly.