DLRで複数のスクリプト言語をホストする方法

DLR (Dynamic Language Runtime)は、一つのランタイムで複数のスクリプト言語をサポートし実行させることなどが出来るものです。今現在、IronPythonIronRubyのベースとなっています。
このDLRを使って、複数のスクリプト言語をホストする方法が意外と書かれてないっぽいので、メモも兼ねて書いてみました。
まぁ、ドキュメントを読めば普通にわかってしまうものですが...

今回は、app.configを書き加えるだけで複数の言語に対応できるコードを書いてみました。

最初に、ScriptRuntimeにConfigurationファイルを使ってScriptRuntimeを生成します。

ScriptRuntime runtime = new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration());

次に、FileInfoなどを使ってファイルの拡張子を渡し、ScriptEngineを生成します。ScriptEngineを生成後は実行するだけです。

if (runtime.TryGetEngineByFileExtension(fileInfo.Extension, out engine))
{
    engine.ExecuteFile(fileInfo.FullName, runtime.CreateScope());
}

尚、下記のようなapp.configファイルを用意すれば一度にPythonRubyスクリプト言語をホスト出来るようになります。

Enjoy!

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting, Version=0.9.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
  </configSections>
  <microsoft.scripting>
    <languages>
      <language names="IronPython;Python;py" extensions=".py" displayName="IronPython 2.0" type="IronPython.Runtime.PythonContext, IronPython, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <language names="IronRuby;Ruby;rb" extensions=".rb" displayName="IronRuby 1.0 Alpha" type="IronRuby.Runtime.RubyContext, IronRuby, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </languages>
    <options>
      <set language="Ruby" option="LibraryPaths" value="..\..\Languages\Ruby\libs\;..\..\..\External\Languages\Ruby\ruby-1.8.6\lib\ruby\site_ruby\1.8\;..\..\..\External\Languages\Ruby\ruby-1.8.6\lib\ruby\site_ruby\;..\..\..\External\Languages\Ruby\ruby-1.8.6\lib\ruby\1.8\" />
    </options>
  </microsoft.scripting>
</configuration>

DLR
http://dlr.codeplex.com/

IronPython
http://www.codeplex.com/IronPython

IronRuby
http://www.ironruby.net/