服务未启动

Service not starting up

这不是 this post 的副本,因为我已经尝试了其中推荐的解决方案。

我一直在尝试将我的 C#/.netCore 3.0/Kestrel 作为服务启动。

在努力让我的应用程序作为服务启动后,我按照这些 instructions 创建了一个新的 exe,结果相同。

发布、添加服务并尝试从 cmd、powershell 或服务界面启动服务后,我收到以下消息提示:

Windows could not start the SomeWorker service on Local Computer. Error 1053: The service did not respond to the start or control request in a timely fashion.

在调查系统事件日志时,我只看到一个通用的:

The myWorker service failed to start due to the following error: The service did not respond to the start or control request in a timely fashion.

当我 运行 exe/console 时,它启动正常,没有任何问题。

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging(
                options => options.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Information))
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>()
                    .Configure<EventLogSettings>(config =>
                    {
                        config.LogName = "Sample Service";
                        config.SourceName = "Sample Service Source";
                    });
            }).UseWindowsService();
}


public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

问题是 Visual Studio 未设置为将服务部署为独立服务。

在项目属性中设置后,一切正常。

不确定这是否有帮助,我遇到了同样的问题。在我的 CreateHostBuilder 方法中归结为:

    host.ConfigureAppConfiguration(
        (hostContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddJsonFile("appsettings.json", false, true);
        }
    );

事实证明不再需要上述内容,因为调用 CreateDefaultBuilder 将设置基本路径并添加 appsettings.json。这是我的 CreateHostBuilder 现在的样子(并且工作正常):

        var host = Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureLogging(loggingBuilder =>
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .Build();
                var logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration)
                    .CreateLogger();
                loggingBuilder.AddSerilog(logger, dispose: true);
            })
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<SrtLmcoMaximoSyncWorker>();
            });
        return host;