Mohammad Taherian
Mohammad Taherian

Reputation: 1694

Getting error in running dynamically compiled C# code

I compiled a c# code dynamically in a .Net Core 3.1 project. I saved the result as a .dll file and trying to use it in another project. In destination project when I add it as a reference and trying to use, I get this error

the type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Private.CoreLib, Version=4.0.0.0.

I tried to compile the code as netstandard 2.1. And also there is reference to System.Private.CoreLib during the compilation in _references but the version is newer than 4.0.0.0.

_references = new List<MetadataReference>();
_references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
_references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.1").Location));
 _references.Add(MetadataReference.CreateFromFile(typeof(Newtonsoft.Json.JsonConvert).GetTypeInfo().Assembly.Location));

How can I solve this issue?

Upvotes: 2

Views: 299

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11163

You need a reference to the netstandard library, which doesn't technically define any types, to match your typeof(object).

    var netstandard = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == "netstandard").Single()

Upvotes: 1

Related Questions