简体   繁体   中英

c# scripting Roslyn session not accepting reference

I am trying to execute some arbitrary c sharp script in a c# .net application, but I have tried numerous ways to add an external file reference of an assembly and it never seems to work complaining I am missing the assembly. the code is as follows:

        var globals = new Globals();
        globals.mventry = myCurrentmventry;
        ScriptState state = null;
        var scriptOptions = ScriptOptions.Default;

        //all the ways I have tried
        var metadata = MetadataReference.CreateFromFile(typeof(MVEntry).Assembly.Location);
        scriptOptions.AddReferences(metadata);     
        scriptOptions.AddReferences(@"\\path\to\Microsoft.MetadirectoryServicesEx.dll");
        scriptOptions.AddReferences(Assembly.GetAssembly(typeof(MVEntry)));       
        CSharpScript.RunAsync(@"string result;
                                if(mventry[""attribute""].Value ==""value"")
                                {result = ""yes"";}
                                else
                                {result = ""no"";}", scriptOptions)
                               .ContinueWith(s => state = s.Result).Wait();
        string result = state.Variables[0].Value.ToString();
        //Also tried this way for fun
        // string result CSharpScript.EvaluateAsync(@"mventry[""attribute""].Value", 
                                scriptOptions,globals);
    }

// my globals class

    public class Globals
    {
        public MVEntry mventry;
    }

No matter how I add the reference or try and execute the script I get:

Microsoft.CodeAnalysis.Scripting.CompilationErrorException: (1,1): error CS0012: The type 'MVEntry' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.MetadirectoryServicesEx, Version=4.1.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

I'm probably doing something glaringly obviously wrong but I just can't see it, indeed when i watch the scriptOptions variable there doesn't seem to be any metadata elements. Any help would be greatly appreciated.

ok it turns out when you are declaring the options type you need to add the options at that point, it must be read only after declared or i'm doing something fundamentally wrong. Anyway here was what worked for me:

var scriptOptions = ScriptOptions.Default
                    .AddReferences(Assembly.GetAssembly(typeof(MVEntry)))
                    .AddImports(Microsoft.MetadirectoryServices);

I added the directives also...it might help someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM