Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# Roslyn Scripting Host Example
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder;
using Roslyn.Scripting;
using Roslyn.Scripting.CSharp;
using Binder = Microsoft.CSharp.RuntimeBinder.Binder;
namespace SignalWire
{
/// <summary>
/// Let us create a quick Scripting Host class.
/// </summary>
public class ScriptingHost
{
private readonly Session _session;
private readonly ScriptEngine _engine;
public ScriptingHost()
: this(null)
{
//Just fall back to the below constructor
}
public ScriptingHost(dynamic context)
{
if (context == null)
context = this;
//Create the script engine
_engine = new ScriptEngine();
//Let us use engine's Addreference for adding some common
//assemblies
new[]
{
typeof (Type).Assembly,
typeof (ICollection).Assembly,
typeof (ListDictionary).Assembly,
typeof (Console).Assembly,
typeof (ScriptingHost).Assembly,
typeof (IEnumerable<>).Assembly,
typeof (IQueryable).Assembly,
GetType().Assembly
}.ToList().ForEach(asm => _engine.AddReference(asm));
//Import common namespaces
new[]
{
"System", "System.Linq",
"System.Collections",
"System.Collections.Generic"
}.ToList().ForEach(ns => _engine.ImportNamespace(ns));
_session = _engine.CreateSession(context);
}
public object Execute(string code)
{
return _session.Execute(code);
}
public void ImportNamespace(string ns)
{
_session.ImportNamespace(ns);
}
public void AddReference(Assembly asm)
{
_session.AddReference(asm);
}
}
//Our Bank
public class DummyBank
{
public DummyBank()
{
//Add some seed accounts for the demo
Accounts = new List<DummyAccount>
{
new DummyAccount(2000, "Joe"),
new DummyAccount(1020, "Jack"),
new DummyAccount(3433, "Jill")
};
}
public List<DummyAccount> Accounts { get; set; }
}
public class DummyAccount
{
public DummyAccount(int balance,string owner)
{
Balance = balance;
Owner = owner;
}
public int Balance { get; set; }
public string Owner { get; set; }
}
public class Driver
{
public static void Main()
{
//Initialize our bank
var bank = new DummyBank();
//Create an instance of our scripting host with bank as the context
//that'll be used to create the session
var host = new ScriptingHost(bank);
string codeLine;
Console.Write(">");
while ((codeLine = Console.ReadLine()) != "Exit();")
{
try
{
//Execute the code
var res = host.Execute(codeLine);
//Write the result back to console
if (res != null)
Console.WriteLine(" = " + res.ToString());
}
catch (Exception e)
{
Console.WriteLine(" !! " + e.Message);
}
Console.Write(">");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.