在将 Worker 服务发布为 Windows 服务后,它一直失败并显示错误:System.NullReferenceException

问题描述

worker 服务是 .net core 3.1,当我在 VS 2019 上运行它时它可以工作(调试和发布),但是在使用 sc.exe 部署/发布和安装它后,它一直失败并显示错误Object reference not set to an instance of an object

我已经检查过,我觉得唯一的一点是原因,可能来自 DI(不应该是,因为它在 VS 2019 上运行良好),还有 appsettings.jsonappsettings.Development.json包含在发布的文件中(所以我看不出为什么 IOptionsMonitorIServiceScopeFactory 应该失败)

解决方法

默认情况下,在将工作服务安装为 windows 服务后,它会将运行所需的文件复制到 TEMP 文件夹中,如果您使用默认值 (sc) 安装 LocalSystem,具有文件夹模式 C:\WINDOWS\TEMP\.net\<executable-name>\<random-hash>\

appsetings.json 或任何设置文件不会复制到那里(请参阅 microsoft doc)。

因此需要将 IHostBuilderIConfigurationBuilder 指向设置文件所在的位置(更有可能指向发布可执行文件的位置)。

我用以下代码解决了它(通过设置 IConfigurationBuilder 的基本路径):

public static IHostBuilder CreateHostBuilder(string[] args)
{            
    return Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureAppConfiguration((hostContext,config) => {
            
            // Ensure that the appsettings.json files are in same folder with the executable   
            string pathToExe = Process.GetCurrentProcess().MainModule.FileName;
            string dir = Path.GetDirectoryName(pathToExe);
            config.SetBasePath(dir);

        })
        .ConfigureServices((hostContext,services) =>
        {
            services.AddHostedService<Worker>();
        });
}

如需进一步参考,请参阅以下 GitHub 问题 herehere