Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In the following code I need to add my assembly so that the script can make use of its classes:

var options = ScriptOptions.Default.AddImports("MyAssembly");

var code = "using MyAssembly.MyNamespace;" +
           "public class TestClass {" +
           "  public int HelloWorld(int num) {" +
           "    return 5 + num;" +
           "  }" +
           "}";

But the following exception is thrown:

Exception thrown: 'Microsoft.CodeAnalysis.Scripting.CompilationErrorException' in Microsoft.CodeAnalysis.Scripting.dll Microsoft.CodeAnalysis.Scripting.CompilationErrorException: error CS0246: The type or namespace name 'MyAssembly' could not be found (are you missing a using directive or an assembly reference?)

I added the assembly in the host project too. I've also tried the examples from here but they didn't work either.

What is the correct syntax to add an assembly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

The following snippet does the trick:

var path = Assembly.GetAssembly(typeof(MyAssembly.SomeClass)).Location;
var asm = AssemblyMetadata.CreateFromFile(path).GetReference();

var options = ScriptOptions.Default.AddReferences(asm);

This following works too and it uses Linq to get the loaded assembly:

var asm = AppDomain.CurrentDomain.GetAssemblies()
    .SingleOrDefault(assembly => assembly.GetName().Name == "MyAssembly");

This however gets the loaded assemblies. If the assembly you need is not already loaded, get them using Assembly.GetExecutingAssembly().GetReferencedAssemblies().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...