簡體   English   中英

是否可以使用 Roslyn 構建 ASP.Net Core Web 應用程序?

[英]Is that possible to build an ASP.Net Core web application using Roslyn?

我試圖將創建 ASP.NetCore Web 應用程序所需的所有代碼放在一個文本文件中,然后在 ASP.Net Core 3.1 應用程序中讀取它並使用 Roslyn 編譯它並將其保存為 dll 文件。 我嘗試了很多。 我可以為控制台應用程序執行此操作,但不能為 Web 應用程序執行此操作。 這就是我所做的

public void Load(string id, string code, IEnumerable<string> allowedAssemblyNames, IEnumerable<Type> allowedTypes, string path)
{
    try
    {
        var _references = new List<MetadataReference>();
        foreach (var assemblyName in allowedAssemblyNames)
        {
            _references.Add(MetadataReference.CreateFromFile(RuntimeEnvironment.GetRuntimeDirectory() + assemblyName + ".dll"));
        }

        foreach (var type in allowedTypes)
        {
            _references.Add(MetadataReference.CreateFromFile(type.Assembly.Location));
        }
        _references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location));


        var options = new CSharpCompilationOptions(
            OutputKind.DynamicallyLinkedLibrary,
            reportSuppressedDiagnostics: true,
            optimizationLevel: OptimizationLevel.Release,
            generalDiagnosticOption: ReportDiagnostic.Error,
            allowUnsafe: false);

        var syntaxTree = CSharpSyntaxTree.ParseText(code, options: new CSharpParseOptions(LanguageVersion.Latest, kind: SourceCodeKind.Regular));
        var compilation = CSharpCompilation.Create(id, new[] { syntaxTree }, _references, options);

        assemblyLoadContext = new AssemblyLoadContext(id, true);

        using (var ms = new MemoryStream())
        {
            var result = compilation.Emit(ms);
            if (result.Success)
            {
                ms.Seek(0, SeekOrigin.Begin);
                bytes = ms.ToArray();
                File.WriteAllBytes(path, bytes);
                ms.Seek(0, SeekOrigin.Begin);
                assembly = assemblyLoadContext.LoadFromStream(ms);
            }
        }
    }
    catch (Exception ex)
    {
        throw;
    }

}

這可能嗎?

在花了一些時間之后,根據GitHub的討論,似乎不可能做到這一點。

給出的答案是:

我認為 .NET Core 不支持直接針對 System.Private.CoreLib.dll 進行編譯。 一般來說,不使用dotnet工具和 MSBuild 編譯應用程序可能會非常困難,因為您必須有效地復制所有邏輯來選擇適當的引用程序集,然后為 .NET 生成正確的執行環境核心共享加載器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM