This project has moved and is read-only. For the latest updates, please go here.

Is there a way to AddHostType with the object named in a string?

Apr 4, 2016 at 6:55 AM
I've asked this over on StackOverflow but have included the full question here to save your mouse.

I define JSengine as
    static JScriptEngine JSengine = null;
instantiate it in Main as
    JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);
and then hook various C# objects into it, e.g.
    static void JSSetup(JScriptEngine jse)
        jse.AddHostType("CSString", typeof(String));
        jse.AddHostType("CSConsole", typeof(Console));
        jse.AddHostType("CSFile", typeof(File));
        jse.AddHostType("CSFileInfo", typeof(FileInfo));
        jse.AddHostType("CSDirectory", typeof(Directory));
        jse.AddHostType("CSPath", typeof(Path));
What I want to know is this: Is there a means whereby I may Add an HostType by specifying it as a string so that I can do something like
The reason for this madness is a desire to be able specify
in a configuration file and therefore be able to control what symbols get made available to the called script.
Apr 4, 2016 at 2:41 PM
Edited Apr 7, 2016 at 4:03 PM

Yes, ClearScript provides AddHostType overloads that let you specify the type by name. For example:
jse.AddHostType("Random", "System.Random");
However, there are some considerations. First, the above code works only if the type resides in mscorlib or in the currently executing assembly. For other types, you can specify the assembly:
jse.AddHostType("Enumerable", "System.Linq.Enumerable", "System.Core");
However, you might want to avoid doing so. Identifying an assembly based on a short name like "System.Core" requires an expensive brute-force search that incurs a large one-time performance hit (the results of the search are saved in a file for subsequent reuse).

Our recommended approach is to load the type manually via Type.GetType. For non-mscorlib types this does require an assembly-qualified name:
jse.AddHostType("Enumerable", Type.GetType("System.Linq.Enumerable, System.Core, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
Good luck!