Publish .NET Core App As Portable Executable

前端 未结 3 1368
暖寄归人
暖寄归人 2020-12-01 07:05

I have a simple .net core app and publish it by following command:

 dotnet publish -c Release -r win10-x64

SqlLocalDbStarter.csproj

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 07:25

    Before .NET Core 3.0

    dotnet publish -r win-x64 -c Release --self-contained
    

    Pretty self explanatory:

    • Publish the project from the current directory.
    • Build the project to run on Windows 64 bit machines.
    • Build in release configuration mode
    • Publish everything as “self-contained” so that everything required to run the app is packaged up with our executable

    So this works right, we end up with a folder that has our exe and everything that is required to run it, but the issue is that there is a tonne required to run even a HelloWorld console app.

    After .NET Core 3.0

    dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
    

    All this does is runs our publish command but tells it to package it within a single file. You’ll notice that we no longer specify the self-contained flag. That’s because it’s assumed that if you are packaging as a single exe, that you will want all it’s dependencies along with it. Makes sense.

    A single tidy exe! When this is executed, the dependencies are extracted to a temporary directory and then everything is ran from there. It’s essentially a zip of our previous publish folder! I’ve had a few plays around with it and honestly, it just works. There is nothing more to say about it. It just works.

    File Size And Startup Cost

    • Keen eyes will notice something about the above screenshot. The file size. It’s over 70MB! That’s crazy for an application that does nothing but print Hello World to the screen! This is solved in Preview 6 of .NET Core 3.0 with a feature called IL Linker or Publish trimmer that omits DLL’s that aren’t used.
    • The other issue you may find is that there is a slight startup cost when running the self contained executable for the first time. Because it needs to essentially unzip all dependencies to a temporary directory on first run, that’s going to take a little bit of time to complete. It’s not crazy (5 seconds or so), but it’s noticeable. Luckily on subsequent runs it uses this already unzipped temp folder and so startup is immediate.

    Modify the csproj and add PublishTrimmed = true.

    
    
      
    
        Exe
    
        netcoreapp3.0
    
        true
    
      
    
    
    

    Now run the below command:

    dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
    

    Reference:

    1. https://dotnetcoretutorials.com/2019/06/20/publishing-a-single-exe-file-in-net-core-3-0/
    2. https://www.hanselman.com/blog/MakingATinyNETCore30EntirelySelfcontainedSingleExecutable.aspx

提交回复
热议问题