简体   繁体   中英

Running scripts inside C#

I want to run javascript/Python/Ruby inside my application.

I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process. For example, the created process will have some activities and in the middle the script should be run and then the process continues as before. Is there a mechanism to run those scripts from C#?

Basically, you have two problems: how to define point of injections in your generated code, and how to run python / ruby / whatev scripts from there.

Depending on how you generate the process, one possible solution would be to add a function to each possible point of injection. The function would check, whether the user has associated any scripts with given points, and if so, runs the script by invoking IronPython / IronRuby (with optionally given parameters).

Disadvantages include: limited accessibility from the scripts to the created process (basically, only variables passed as parameters could be accessed); as well as implementation limits (IronPython's current version omits several basic system functions).

查看IronPython和IronRuby - 这些将使您可以轻松地与C#进行互操作。

You can compile C# code from within a C# application using the CSharpCodeProvider class.

If the compile succeeds you can run the resulting assembly as returned via the CompiledAssembly property of the CompilerResults class.

令人敬畏的C#脚本语言 - Script.Net

.NET有一种脚本语言,包括PowerShell中的运行时引擎,可以嵌入到任何.NET应用程序中。

You can compile C# code "on the fly" into an in-memory assembly. I think this is possible with IronPython and IronRuby as well. Look at the CodeDomProvider.CreateProvider method.

If you need to run scripts a lot, or if your process runs for a long time, you might want to load these assemblies into another AppDomain. And unload the AppDomain after you're done with the script. Otherwise you are unable to remove them from memory. This has some consequenses on the other classes in your project, because you have to marshall all calls.

Have you thought about Visual Studio for Applications? I haven't heard much about it since .NET 1.1, but it might be worth a look.

http://msdn.microsoft.com/en-us/library/ms974548.aspx

I've done exactly this just recently - allowed run-time addition of C# scripting.

It's not hard at all, and this article:

http://www.divil.co.uk/net/articles/plugins/scripting.asp

is a very useful summary of the details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM