Linh.CodeEngine 1.0.3

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

Linh.CodeEngine

NuGet Version License: MIT

Linh.CodeEngine is a powerful and flexible .NET 8 library that allows you to compile and execute C# code dynamically at runtime. Built on top of the Roslyn compiler platform, this library is the perfect solution for building extensible systems, such as plugin platforms, rule engines, or scripting systems.

The library is designed for seamless integration into ASP.NET Core applications.

The Problem It Solves

In many complex systems, business logic often changes (e.g., promotional formulas, approval workflows, payroll calculations). Hard-coding this logic requires code changes, a full application rebuild, and a new deployment for every update.

Linh.CodeEngine solves this by enabling you to:

  • Store business logic as C# code strings in a database or file system.
  • Compile and execute that logic "hot" without restarting the application.
  • Update, activate, or deactivate these logic modules flexibly via an API.

Key Features

  • Runtime Compilation: Utilizes the Roslyn API to compile C# code from strings or files.
  • Lifetime Management: Supports Singleton, Scoped, and Transient lifetimes for dynamic modules, deeply integrating with ASP.NET Core's Dependency Injection.
  • Type-Safe & Flexible Execution:
    • Execute via a common interface (IDynamicAction<TIn, TOut>) for type safety.
    • Execute any method via Reflection for classes that don't implement the interface, with full support for both synchronous and asynchronous (async Task) methods.
  • Assembly Isolation: Uses custom AssemblyLoadContext to load and unload assemblies, preventing conflicts and memory leaks.
  • Pluggable Storage: Provides a built-in Storage Provider for the File System and can be easily extended for EF Core or other databases.
  • Built-in API (Optional): Can ship with a pre-built DynamicCodeAdminController to manage code modules out of the box.

Installation

You can install the package from the NuGet Gallery.

dotnet add package Linh.CodeEngine

Quick Start Guide

Integrating the engine into an ASP.NET Core application involves two main steps: Service Registration and Application Configuration.

  1. In Program.cs, register the engine's services.

    Add the AddDynamicCodeEngineWithFileSystem extension method to your service configuration.

    // Program.cs
    using Linh.CodeEngine.Extensions; // Add this using directive
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add your other services...
    builder.Services.AddControllers();
    
    // --- 1. REGISTER LINH.CODEENGINE SERVICES ---
    var storagePath = Path.Combine(builder.Environment.ContentRootPath, "DynamicModules");
    builder.Services.AddDynamicCodeEngineWithFileSystem(storagePath);
    
    var app = builder.Build();
    
    // ...
    
  2. Configure the engine to load modules on application startup.

    Immediately after the app is built, call the ConfigureCodeEngine extension method. This is an asynchronous call that will load all active modules from your chosen storage provider.

    // Program.cs (continued)
    var app = builder.Build();
    
    // --- 2. CONFIGURE AND LOAD MODULES ON STARTUP ---
    await app.ConfigureCodeEngine();
    
    // Configure your HTTP request pipeline
    if (app.Environment.IsDevelopment())
    {
        // ...
    }
    
    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();
    
  3. Use DynamicCodeManager in your application.

    Once configured, you can access the DynamicCodeManager via Dependency Injection (recommended) or through the globally available singleton instance.

    Option 1: Using Dependency Injection (Recommended)

    [ApiController]
    [Route("[controller]")]
    public class MyBusinessController : ControllerBase
    {
        private readonly DynamicCodeManager _codeManager;
    
        // Inject via the constructor
        public MyBusinessController(DynamicCodeManager codeManager)
        {
            _codeManager = codeManager;
        }
    
        [HttpGet("calculate-tax")]
        public IActionResult CalculateTax([FromQuery] decimal orderAmount)
        {
            var result = _codeManager.Execute<decimal, decimal>(
                "SimpleTaxCalculator",
                orderAmount
            );
    
            if (result.IsSuccess)
            {
                return Ok(new { TaxAmount = result.Output });
            }
            return BadRequest(result.ErrorMessage);
        }
    }
    

    Option 2: Using the Singleton Instance (if injection is not possible)

    public class SomeOtherService
    {
        public void DoSomething()
        {
            // Access directly via the Singleton
            var codeManager = Singleton<DynamicCodeManager>.Instance;
            var result = codeManager.Execute<string, bool>("MyValidationRule", "some-input");
            // ...
        }
    }
    

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Made with ❤️ by Linh Nguyen.

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.0.3 118 7/16/2025

Initial release of the Dynamic Code Engine.
- Core features: Compile, Load, and Execute C# code.
- Storage providers: FileSystem.
- Lifetime management: Singleton, Scoped, Transient.
- Includes a built-in Admin API Controller.