【问题标题】:Is that possible to build an ASP.Net Core web application using Roslyn?是否可以使用 Roslyn 构建 ASP.Net Core Web 应用程序?
【发布时间】:2020-01-24 23:50:37
【问题描述】:

我正在尝试将创建 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;
    }

}

这可能吗?

【问题讨论】:

  • @ChristopherPainter 谢谢。我以前试过那个页面。它展示了如何创建不同的类并运行它,但我需要从头开始创建一个新网站。它包含Program 类、main 方法、Startup 类等。我可以这样做吗?

标签: c# .net-core roslyn roslyn-code-analysis


【解决方案1】:

花了一些时间之后,基于a discussion on GitHub,似乎不可能做到这一点。

给出的答案是:

我认为.NET Core 不支持直接编译 针对 System.Private.CoreLib.dll。一般来说,它可能是 不使用dotnet 很难编译应用程序 工具和 MSBuild,因为您必须有效地复制所有 选择适当的参考程序集的逻辑, 然后为 .NET Core 生成正确的执行环境 共享加载器。

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    相关资源
    最近更新 更多