2

I am using Roslyn to compile and run C# scripts entered by the user. I would like to dynamically react to the script choosing different assemblies to load (for example, adding 'using System.Net.Http' to access HttpClients)

My current implementation is similar to the example at https://www.albahari.com/nutshell/E8-CH27.aspx, but I have a few additional steps where I emit the compilation, grab any errors such as

error CS1069: The type name 'HttpClient' could not be found in the namespace 'System.Net.Http'. //This type has been forwarded to assembly 'System.Net.Http, Version=4.2.2.0, //Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' Consider adding a reference to that assembly.

then parse the Assembly name, search if there are any matching names in var allTrustedAssemblies = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"); , add the reference, then compile and emit again. This loops until the compilation succeeds or the errors and reference updates stagnate.

                if (requiredAssemblyName != null)
                {
                    var matchingAssemblies = trustedAssembliesPaths
                    .Where(p => requiredAssemblyName.Contains(Path.GetFileNameWithoutExtension(p)))
                    .Select(p => MetadataReference.CreateFromFile(p));

                    metaDataReferences.AddRange(matchingAssemblies);
                }

This seems to work in .NET Core, but AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is null when running in Framework. How can I get a list of all valid assemblies on my system and their paths when targeting Framework 4.8?

I am also open to suggestions on other implementations, such as parsing the namespace causing issues, finding the assembly associated with it, and then dynamically updating the 'typeof' MetadataReference.CreateFromFile(typeof(foo).Assembly.Location),

I reviewed https://learn.microsoft.com/en-us/dotnet/framework/deployment/how-the-runtime-locates-assemblies

The GAC may be the key, but I am not certain how to choose the appropriate folder relative to what framework the program running the script is targeting

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.