OdeToCode IC Logo

Hosting A JavaScript Engine In .NET

Tuesday, September 10, 2013

ClearScript is simple to use and allows me to host either V8 or Chakra. The samples on the home page show just how easy is the interop from C# to JavaScript and vice versa.

I use a simple wrapper because the only API I need is one to Evaluate small script expressions.

public interface IJavaScriptMachine : IDisposable
{
    dynamic Evaluate(string expression);
}

The following implementation sets up a default environment for script execution by loading up some required scripts, like underscore.js. The scripts are embedded resources in the current assembly.

public class JavaScriptMachine : JScriptEngine, 
                                 IJavaScriptMachine
{      
    public JavaScriptMachine()
    {
        LoadDefaultScripts();                
    }
    
    void LoadDefaultScripts()
    {
        var assembly = Assembly.GetExecutingAssembly();
        foreach (var baseName in _scripts)
        {
            var fullName = _scriptNamePrefix + baseName;
            using (var stream = assembly.GetManifestResourceStream(fullName))
            using(var reader = new StreamReader(stream))
            {
                var contents = reader.ReadToEnd();
                Execute(contents);
            }
        }
    }

    const string _scriptNamePrefix = "Foo.Namespace.";
    readonly string[] _scripts = new[]
        {
            "underscore.js", "other.js"
        };       
}

For examples, check out the ClearScript documentation.