Hi There

 

I know. the art of compiling in realtime is something scaring because of the great drawbacks and security concerns this choice bring together with the great flexibility of dynamically run new compiled code

 

Although this, often clients ask me for having the ability to write some little (usually mathematical) function to customize some computation without having to rely on configuration files and obviously without having to compile and deploy again the whole application

 

a solution came with a NuGet package from my company, the TNX.CrossDomainContext where lie a class that names RuntimeCompiler. here an example

 

var result = RuntimeCompiler.InvokeFunction<int, int>(“x * x”, 10);
Assert.IsTrue(result.Succeded);
Assert.AreEqual<int>(result.Result, 100);

 

the usage is definitely easy. in the string parameter we write a simple inline function written in C# 4.0

within we have the ability to use the parameter “x” that here is of int type but can be of any struct type!!!

 

the compilation and execution result is given by the RuntimeCompilerResult class that came by InvokeFunction invocation. Here you will find a Succeded property, the needed Result, an eventual Exception and a diagnostic information about total execution time

 

the execution is completely temporary and the generated assembly is loaded in a sanboxed AppDomain unloaded asap as the inner code teminate

 

this feature is also available by itself by using the AppDomainContext class from the same package

 

using (var appcontext = new AppDomainContext<int, int>())
{
    int result;
    appcontext.TryExecuteFunc(i => 10, 0, out result);
}

 

this class easily let execute a target method provided by a delegate in a sandboxed AppDomain

 

hope those features will be useful to someone

bye

One thought on “Compiling CSharp at runtime in a reliable way”

Lascia un commento