Table of Contents
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.
The following open source packages are used in this project:
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.
- 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.
