Matjaž Mav Matjaž Mav - 1 year ago 98
C# Question

Roslyn scripting with enforced script interface

I have simple

interface. And I want enforce that all scripts implement it.

public interface IScript<T>
T Execute(object[] args);

I want to use Roslyn scripting API to achive this. Something like this is possible with CSScript (see Interface Alignment).

var code = @"
using System;
using My.Namespace.With.IScript;

public class Script : IScript<string>
public string Execute()
return ""Hello from script!"";

var script = CSharpScript.Create(code, ScriptOptions.Default); // + Load all assemblies and references
script.WithInterface(typeof(IScript<string>)); // I need something like this, to enforce interface

string result = script.Execute(); // and then execute script

Console.WriteLine(result); // print "Hello from script!"

Answer Source

Type safety is a static thing enforced a compile time (of your application). Creating and running a CSharpScript is done at runtime. So you cannot enforce type safety at runtime.

Maybe CSharpScript is not the right way to go. By using this SO answer, You can compile a piece of C# code into memory and generate assembly bytes with Roslyn.

You would then change the line

object obj = Activator.CreateInstance(type);


IScript<string> obj = Activator.CreateInstance(type) as IScript<string>;
if (obj != null) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download