[英]Is that possible to build an ASP.Net Core web application using Roslyn?
I am trying to put all the codes that is needed to create an ASP.NetCore Web Application in a text file and then read it in an ASP.Net Core 3.1 application and compile it using Roslyn and save it as a dll file.我试图将创建 ASP.NetCore Web 应用程序所需的所有代码放在一个文本文件中,然后在 ASP.Net Core 3.1 应用程序中读取它并使用 Roslyn 编译它并将其保存为 dll 文件。 I tried a lot.
我尝试了很多。 I could do that for a Console application but not for a web application.
我可以为控制台应用程序执行此操作,但不能为 Web 应用程序执行此操作。 This is what I did
这就是我所做的
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;
}
}
Is that possible at all?这可能吗?
After spending some time on it, based on a discussion on GitHub , it seems it is not possible to do that.在花了一些时间之后,根据GitHub上的讨论,似乎不可能做到这一点。
The answer given was:给出的答案是:
I believe it's considered unsupported by .NET Core to compile directly against System.Private.CoreLib.dll.
我认为 .NET Core 不支持直接针对 System.Private.CoreLib.dll 进行编译。 In general, it will probably be quite difficult to compile an application without using the
dotnet
tool and MSBuild, as you will have to effectively replicate all the logic that goes into picking the appropriate reference assemblies, then generating the right executing environment for the .NET Core shared loader.一般来说,不使用
dotnet
工具和 MSBuild 编译应用程序可能会非常困难,因为您必须有效地复制所有逻辑来选择适当的引用程序集,然后为 .NET 生成正确的执行环境核心共享加载器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.