aspnetcore: Minimal host does not work with NativeAOT

Describe the bug

While this isn’t yet a fully supported scenario it was possible to build simple ASP.NET Core applications before with NativeAOT. This should in theory still be possible since the WebApplicationBuilder is a thin layer over the existing APIs. That’s broken now because we’re using Assembly.GetCallingAssembly to get the default application name.

To Reproduce

csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>

<ItemGroup>
    <PackageReference Include="Microsoft.DotNet.ILCompiler" Version="6.0.0-*" />
</ItemGroup>

</Project>

Program.cs

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", context => context.Response.WriteAsync("Hello World!"));

app.Run();
  1. Run dotnet publish -r win-x64 (I was on windows)
  2. Run the resulting published exe.

Exceptions (if any)

WebApplication1\bin\Debug\net6.0\win-x64\publish\WebApplication1.exe
Unhandled Exception: System.PlatformNotSupportedException: Operation is not supported on this platform.
   at System.Reflection.Assembly.GetCallingAssembly() + 0x7a
   at Microsoft.AspNetCore.Builder.WebApplication.CreateBuilder(String[]) + 0x1d
   at <Program>$.<Main>$(String[]) + 0x3e
   at WebApplication1!<BaseAddress>+0x1080f37
   at WebApplication1!<BaseAddress>+0x1080fc5

cc @MichalStrehovsky @jkotas @agocke

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 16 (16 by maintainers)

Most upvoted comments

GetCallingAssembly is slow and unreliable API that does not work well with NativeAOT. It does not work in Mono AOT either - https://github.com/dotnet/runtime/issues/53825. I do not see us fixing that.

I think we need a small language feature to get fast, reliable and AOT-friendly replacement for the scenarios where it is used: https://github.com/dotnet/runtime/issues/41690#issuecomment-685092071

Yea I know why it’s broken, I’m just filing an issue so we can resolve it

NativeAOT doesn’t support GetCallingAssembly, because all assemblies are linked and “inlined” so there’s no so called “calling assembly”.

To workaround, use

  <ItemGroup>
    <RuntimeHostConfigurationOption Include="Switch.System.Reflection.Assembly.SimulatedCallingAssembly" Value="true" />
  </ItemGroup>

which simulates Assembly.GetCallingAssembly using Assembly.GetEntryAssembly.

https://github.com/dotnet/aspnetcore/blob/0c5456afe95096db6ac5400cecd3440299b42714/src/DefaultBuilder/src/WebApplication.cs#L89 https://github.com/dotnet/aspnetcore/blob/0c5456afe95096db6ac5400cecd3440299b42714/src/DefaultBuilder/src/WebApplication.cs#L97

I’m seeing callingAssembly can be null, so I think it here can detect if it’s supported to determine whether to call Assembly.GetCallingAssembly() or not.