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

Reuse script engine instance

May 22, 2015 at 1:48 PM
Dear Sirs,
I wonder what would be your advice on how to implement reuse of JScriptEngine instance or is it at all advisable.
Given that assemblies, types and libraries of helper scripts are all the same between two sample scripts and are all loaded, is it possible to unload first script with its host objects and load the second with its own set of host objects.
Immediate issue for me was not being able to use AddHostObject() to set new object in case when name of host objects match between scripts.

Please advise.

May 22, 2015 at 4:39 PM
Hello MW,

It's certainly possible to execute multiple scripts sequentially within a given script engine instance, and no unloading is necessary in between. However, a malicious or buggy script could easily corrupt the environment for subsequent scripts – by deleting or replacing built-in objects, leaving unexpected objects in the root namespace, etc.

Therefore a careful evaluation of script trust level is always a good idea, combined with an assessment of the impact of a corrupted script environment. Some applications such as web browsers rely on the ability to execute multiple untrusted scripts within the same context, and have robust mechanisms for detecting and discarding contexts that are stuck or otherwise problematic.

The bottom line is that if it's important that all scripts start out in a pristine environment, and you cannot assume that each script will clean up after itself, then you should create a new context (script engine instance) for each one.

On a separate note, if you need to expose a host object in a way that allows it to be replaced later, consider using dynamic property assignment instead of AddHostObject(): = new Foo();
// or
engine.Script["foo"] = new Foo();
Good luck!