Skip to content

ChristopherVR/DynamicExecutor

Repository files navigation

NET Logo

Dynamic Code Compiler & Executor in C# .NET 7

This is a demonstration on how to compile dynamic code and execute it at runtime.

Note: This project is still a WIP


📖 Table of Contents

Table of Contents
  1. ➤ About The Project
  2. ➤ Prerequisites
  3. ➤ Setup
  4. ➤ Examples

-----------------------------------------------------

📝 About The Project

This project aims to provide a proof of concept on how one can use Roslyn API (CodeAnalysis nuget package) to execute dynamic code with ease. This might be helpful in cases where one needs to build dynamic reports and/or pages.

-----------------------------------------------------

🍴 Prerequisites

Made with-dot-net
build status

The following open source packages are used in this project:

-----------------------------------------------------

💻 Setup

A: Register the AnalyseCodeService & DynamicCodeService on your startup:

builder.Services.AddSingleton<IAnalyseCodeService, AnalyseCodeService>();
builder.Services.AddSingleton<IDynamicCodeService, DynamicCodeService>();

Note: IHttpContextAccessor is required for these services.

B: View the IDynamicCodeService interface to see what method overload would be most appropriate for you to use.

C: See the Examples on how to execute code in this service and retrieve a response.

-----------------------------------------------------

🎯 Examples

  • Executing a basic Console application:
// Use DI as required.
IDynamicCodeService dynamicService = new DynamicCodeService(logger, _httpContextAccesor, mockServiceScope, mockAnalyseCodeService, mockOptions);

// Act
int res = await dynamicService.ExecuteCodeAsync<int>($@"using System; Console.WriteLine(""Hello world!""); return int.Parse(args[0]);", c =>
{
    c.ExecuteAsConsoleApplication = true;
}, cancellationToken: CancellationToken.None, new object[] { new string[] { "2" } });

// Assert
Assert.Equal(2, res);

See the unit tests file for more examples here.

-----------------------------------------------------

About

.NET class library to compile and execute dynamic C# code.

Resources

Stars

Watchers

Forks