Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force CSharpCodeProvider to compile for a specific target framework?

Tags:

c#

roslyn

codedom

I've got a solution which contains c# projects, some netstandard 2.0 and others .net4.7. The startup project is of course net47.

At one point, the project creates code using CodeDom and compiles it with CSharpCodeProvider. The problems is that on some machines, it tries to compile the assembly for .netstandard and it fails. The failure is expected: the generated assembly references EF which in only available for full .net framework.

How can I force CSharpCodeProvider to compile against .net47?

public bool GenerateAssembly(
        CodeDomBusinessCode compileUnit
        , string fileName
        , string assembliesPath
        , out IEnumerable<string> errors)
    {
        var provider = new CSharpCodeProvider();
        var parameters = new CompilerParameters
        {
            GenerateExecutable = false,
            OutputAssembly = fileName,
            GenerateInMemory = false
        };
        parameters.ReferencedAssemblies.Add("System.dll");
        parameters.ReferencedAssemblies.Add("System.Runtime.dll");
        parameters.ReferencedAssemblies.Add("System.Core.dll");
        parameters.ReferencedAssemblies.Add("System.ComponentModel.Composition.dll");
        parameters.ReferencedAssemblies.Add(Path.Combine(assembliesPath, "EntityFramework.dll"));
        parameters.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
        parameters.ReferencedAssemblies.Add(Path.Combine(assembliesPath, "GlobalE.Server.Contracts.dll"));

        var results = provider.CompileAssemblyFromDom(parameters, compileUnit.Code);
        if (results.Errors.Count > 0)
        {
            errors = results.Errors.OfType<CompilerError>().Select(x => x.ToString());
            return false;
        }
        errors = null;
        return true;
    }

The error:

error CS0012: The type 'System.IDisposable' is defined in an assembly
 that is not referenced. You must add a reference to assembly 
'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

UPDATE: If I change all projects to net47 (so that there is no netstandard project in the solution), the error will disappear, but I want to keep as many projects on netstandard as possible.

like image 858
Alireza Avatar asked Nov 10 '17 09:11

Alireza


1 Answers

based on your error, you should add "netstandard.dll" as references and it may cause by this note that in .net 4.7 the "System.IDisposable" is in "mscorlib.dll" and in .netstatndard is in "netstandard.dll".

like image 110
Pbehin Avatar answered Oct 07 '22 11:10

Pbehin