我正在使用Roslyn使用运行时生成的代码来编译解决方案。虽然从Visual Studio打开该解决方案可以完美地编译,但从Roslyn失败:
错误CS5001:程序不包含适用于入口点的静态“ Main”方法
我尝试编译的解决方案只有一个ASP.NET Core 2(.NET Framework 4.6.2)项目,该项目当然在项目根目录的Program类中具有Main方法:
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我正在运行的用于从.NET 4.7 WPF应用程序编译该解决方案的代码:
private static async Task<bool> CompileSolution(string solutionPath, string outputDir)
{
var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath);
var projectCompilation = await solution.Projects.Single().GetCompilationAsync();
if (string.IsNullOrEmpty(projectCompilation?.AssemblyName))
{
return false;
}
using (var stream = File.Create(Path.Combine(outputDir, $"{projectCompilation.AssemblyName}.dll")))
{
var result = projectCompilation.Emit(stream);
return result.Success;
}
}
Run Code Online (Sandbox Code Playgroud)
projectCompilation.Emit 失败:
- 警告CS8021:找不到RuntimeMetadataVersion的值。找不到包含System.Object的程序集,也没有通过选项指定RuntimeMetadataVersion的值。
- 错误CS5001:程序不包含适用于入口点的静态“ Main”方法
可能是所使用的NuGet软件包尚未正确支持.NET Core 2项目吗?我没有任何待处理(甚至无法预览)的软件包更新。
现在,我已经将ASP.NET Core项目更新为.NET 4.7,以便两个解决方案的版本都相同,但是没有更改生成的错误。csproj看起来像这样:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net47</TargetFramework>
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
<TargetFrameworkVersion>v4.7</TargetFrameworkVersion>
<ApplicationIcon />
<OutputType>Exe</OutputType>
<StartupObject>Practia.CrudGenerator.Web.Program</StartupObject>
</PropertyGroup>
<ItemGroup>..NUGET PACKAGES...</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
通过在尝试发出结果之前添加这两行来解决了该问题:
compilation = compilation.AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
compilation = compilation.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
Run Code Online (Sandbox Code Playgroud)
注意两个AddReferences和WithOptions返回新的Compilation实例,所以有必要重新分配。