How to use Roslyn in wpf application

54 Views Asked by At

When the same .cs file is compiled into a DLL using Visual Studio, it can run normally in a WPF program. However, when compiling into a DLL using Roslyn, it will cause an error in all windows' InitializeComponent method: "The name 'InitializeComponent' does not exist in the current context."

The runtime is .Net7, here is the core code:

void CompileCode(string codeString)
{
    SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeString);
    var references = new[]
    {
        typeof(object).Assembly,
        Assembly.Load("SqlSugar"),
        Assembly.Load("System.Linq"),
        Assembly.Load("netstandard"),
        Assembly.Load("System.Runtime"),
        Assembly.Load("System"),
    }
    .Select(assembly => assembly.Location)
        .Distinct()
        .Select(l => MetadataReference.CreateFromFile(l))
        .Cast<MetadataReference>()
        .ToArray();
    var DefaultNamespaces =
            new[]
            {
                "System",
                "System.IO",
                "System.Net",
                "System.Linq",
                "System.Text",
                "System.Text.RegularExpressions",
                "System.Collections.Generic"
            };
    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            .WithPlatform(Platform.AnyCpu) 
            .WithOverflowChecks(true)
            .WithOptimizationLevel(OptimizationLevel.Release) 
            .WithUsings(DefaultNamespaces);
    ;
    var runtimePath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); 
    CSharpCompilation cSharpCompilation = CSharpCompilation.Create(tableName)
                    .WithOptions(compilationOptions) 
                    .AddReferences(references) 
                    .AddSyntaxTrees(syntaxTree);
    var assemblyPath = @"D:\myCode\DataTableCS\" + tableName + ".dll";
    var pdbPath = @"D:\myCode\DataTableCS\" + tableName + ".pdb";
    var dll_result = cSharpCompilation.Emit(assemblyPath, pdbPath);     
    
}

cs file as below:

using System;
using System.Linq;
using System.Text;
using SqlSugar;

namespace CommonClass
{
    ///<summary>
    ///
    ///</summary>
    [SugarTable("Tb_Project")]
    public partial class Tb_Project
    {
           public Tb_Project(){


           }
           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:False
           /// </summary>           
           [SugarColumn(IsPrimaryKey=true)]
           public string ID {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? Name {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public decimal? Quantity {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? RootItemID {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? RootItemConfig {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? ProjectNo {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? ProjectManagerID {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? MDPTime {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? Status {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? Description {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public int? Version {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public string? CTime {get;set;}

           /// <summary>
           /// Desc:
           /// Default:
           /// Nullable:True
           /// </summary>           
           public int? del {get;set;}

    }
}

1: Creat a sample wpf C# application 2: then use the CompileCode() to produce the dll by the .cs file 3: attach the dll produced in step 2 to the application 4: windows raises the error

0

There are 0 best solutions below