【问题标题】:Can't create Windows Service that references .NET Core 2.0 assemblies无法创建引用 .NET Core 2.0 程序集的 Windows 服务
【发布时间】:2017-11-18 03:33:14
【问题描述】:

我需要一个非 ASPNET Windows 服务(如旧式控制台应用程序)。我知道我无法在 Visual Studio(仅限 .NET Framework)中创建 Windows 服务并引用任何 Core 1/2 程序集;不允许。

我想利用我的其他 ASPNET 项目的所有工作,例如数据库存储库...已经在 Core 2.0 中。

那么...有什么想法可以编写一个 Windows 服务,以某种方式利用在 Core Visual Studio 项目中创建的工作?

参考:Another post on this topic.

【问题讨论】:

    标签: console windows-services .net-core


    【解决方案1】:

    虽然您可以将一些共享程序集创建为 .NET Standard 而不是 .NET Core,然后在 .NET Framework Windows 服务中使用这些共享程序集,但在创建基于 .NET Core 的 Windows 服务时还有其他选择。

    第一个是使用Windows Compatibility Pack(当前处于预览状态),它允许在 Windows 上运行时在 .NET Core 中使用 ServiceBase 类。

    另一个选择是使用DasMulli.Win32.ServiceUtils NuGet 包,它允许在 .NET Core 和 .NET Framework 上创建 Windows 服务,其 API 与ServiceBase 略有不同 - 请参阅its GitHub repository。 (免责声明:我自己开发的包,供我工作的公司使用)

    【讨论】:

    • 使用 Windows 兼容包的快速测试确实有效...允许我编写 Core 2.0 控制台应用程序(使用 ServiceBase)并参考其他核心项目。谢谢。
    【解决方案2】:

    答案更新

    根据 Martin 的回答和评论 现在您可以使用 Windows 兼容包


    是的,netcoreapp 不能被 net framework 项目引用。https://github.com/dotnet/standard/blob/master/docs/versions.md 的这份文档显示了兼容性矩阵。 根据那个net framework只能引用兼容的netstandard项目。

    进一步根据Api reference for ServiceBase Class ServiceBase 类仅在网络框架中可用。


    我想到在 Windows 服务中利用 netcoreapp 项目的一个选项是使用 netcore2.0 和 net471 创建一个多目标项目,或者使用条件编译使 coreapp 项目成为一个多目标。

    在 csproj 中添加对Microsoft.AspNetCore.Hosting.WindowsServices 的条件引用。然后有条件地在program.cs中调用host.RunAsServicehost.Run

    有关多目标和 Windows 服务的更多信息,请查看

    1. How to Multitarget section in Developing Libraries with cross platform tools
    2. Host an ASP.NET Core app in a Windows Service

    【讨论】:

      猜你喜欢
      • 2018-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多