Consider automatically loading references from target project
Consider loading the references that the host project uses and making them available in the script. Maybe there should be a preprocessor directive to opt-in to this behavior.
... or making an event handler available for AppDomain.Current.AssemblyResolve in case the assembly isnt nearby.
This would load the current references and namespaces. If it needs to be configurable it could use a new entry on Tools --> Options -->Scripty Options for global. Using the file properties where the custom tool is specified would be another config point.
I didnt find a clear distinction between the pairs of .Add()* or .With*() methods on script options, but these work (and i didnt really look that hard).
var scriptFullPath = Path.GetFullPath(scriptName);
var scriptCode = File.ReadAllText(scriptFullPath);
var scriptOptions = ScriptOptions.Default
.WithFilePath(scriptFullPath);
var currentRefs = AppDomain.CurrentDomain.GetAssemblies();
foreach (var asmRef in currentRefs)
{
scriptOptions.WithReferences(asmRef);
if (asmRef.FullName.Contains("mscorlib"))
{
continue;
}
try
{
var namepsaces = asmRef.GetTypes()
.Where(t => string.IsNullOrWhiteSpace(t.Namespace) == false)
.Select(t => t.Namespace);
scriptOptions.AddImports(namepsaces.Distinct());
}
catch (ReflectionTypeLoadException reflx)
{
Console.WriteLine($"Skipping assembly {asmRef.FullName}. Err: {reflx}");
}
}
var script = CSharpScript.Create(scriptCode, scriptOptions, typeof(T));
var result = script.RunAsync(globalsInstance).Result;
return result;
}