无法使用 Serilog 在 Docker 上启动 .NET Core 3.1 Worker Service

Unable to start .NET Core 3.1 Worker Service on Docker using Serilog

我正在使用 Visual Studio 2019(Docker 支持已启用)编写 .Net Core 3.1 Worker Service 应用程序。

如果我使用 Docker 启动应用程序,一切正常,但是当我向项目添加 Serilog.AspNetCore 3.4.0 依赖项时,我无法再使用 docker 进行调试。

案例:

Visual Studio返回的错误是:

这是控制台返回的错误:

-------------------------------------------------------------------
You may only use the Microsoft .NET Core Debugger (vsdbg) with
Visual Studio Code, Visual Studio or Visual Studio for Mac software
to help you develop and test your applications.
-------------------------------------------------------------------
It was not possible to find any compatible framework version
The framework 'Microsoft.AspNetCore.App', version '3.1.0' was not found.
  - No frameworks were found.

You can resolve the problem by installing the specified framework and/or SDK.

The specified framework can be found at:
  - https://aka.ms/dotnet-core-applaunch?framework=Microsoft.AspNetCore.App&framework_version=3.1.0&arch=x64&rid=debian.10-x64
The program 'dotnet' has exited with code 150 (0x96).

编辑:

这是VS 2019自动生成的Dockerfile:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["MensaNotificationService/MensaNotificationService.csproj", "MensaNotificationService/"]
RUN dotnet restore "MensaNotificationService/MensaNotificationService.csproj"
COPY . .
WORKDIR "/src/MensaNotificationService"
RUN dotnet build "MensaNotificationService.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MensaNotificationService.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MensaNotificationService.dll"]

问题是什么,我该如何解决?

错误很明显 - ASP.NET 核心运行时缺失。这甚至不是 Visual Studio 错误,因为 Worker Service 模板旨在创建后台进程,而不是 Web 应用程序。 .NET 运行时本身不包括 ASP.NET 核心运行时。

如果您想在辅助服务中将 Serilog 与 Microsoft.Extensions.Logging 一起使用,请使用 Serilog.Extensions.Hosting or Serilog.Extensions.Logging package, not Serilog.AspNetcoreAspNetCore 软件包将 ASP.NET 核心特定扩展添加到 Serilog.Extensions.Hosting

如果你真的想托管一个带有长 运行 服务的网络应用程序作为守护进程,你需要将运行时更改为 `aspnet.这也显示在 Dockerize an ASP.NET Core application 中。 docker 文件示例使用:

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "aspnetapp.dll"]

不过,更好的解决方案是使用 ASP.NET 核心模板之一并向其添加 BackgroundService。