运行 ASP.NET .NET 3.0 中的 Worker Service 核心

Running ASP.NET Core on Worker Service in .NET 3.0

我已经成功构建了一个 Worker Service 并添加了 ASP.NET Core API 到工作正常的服务中。我面临的问题是将其安装为 windows 服务。自从升级到 .NET 3.0 以来,有很多重大变化,尤其是 HostBuilder

下面是我的Program class

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostcontext, svc) =>
            {
                svc.AddHostedService<Worker>();
            });

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1044);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });

当我 运行 时,它无法选择 WebHost Builder,而当我 运行 仅使用 WebHost 构建器时,它无法在目标服务器上安装服务。

请协助 我想利用 IWebHostBuilderIHostBuilder 的优点,但我不知道如何在 static main 方法中结合它们。

下面是其他文件;

StartUp

 public void ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services)
        {
            services.AddHostedService<Worker>();

            ////Add Controllers
            //services.AddTransient<SalesForceDataLoaderController>();


            //Add DB Dependency Injection
            services.AddAutoMapper(typeof(Startup));

            services.AddMvc().AddJsonOptions(options =>
            {
                options.UseCamelCasing(true);
            }).AddControllersAsServices();
            services.AddDbContext<SalesForceReportLoaderContext>(options =>
                options.UseSqlServer(this.APIdb));

            services.AddScoped<IRepositoryWrapper, RepositoryWrapper>();
            services.AddScoped<ILogger, Logger<SalesForceDataLoaderController>>();
            services.AddScoped<ILogger, Logger<ActisureWhatsAppController>>();
            services.AddScoped<ILogger, Logger<PureWhatsAppController>>();

            services.AddSingleton(typeof(IRepository<>), typeof(Repository<>));
            services.AddSingleton<ISalesforceLoaderRepository, SalesforceLoaderRepository>();
            services.AddSingleton<IActWhatsAppClaimStatusRepo, ActWhatsAppClaimStatusRepo>();
            services.AddSingleton<IPureWhatsAppClaimStatusRepo, PureWhatsAppClaimStatusRepo>();
            services.AddSingleton<IPureWhatsAppPolicyDetailsRepo, PureWhatsAppPolicyDetailsRepo>();


        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMvc();
            //app.UseRouting();

        }

和我的worker class

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

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

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Service Starting at: {time}", DateTimeOffset.Now);
            return base.StartAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    //Run a request

                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.InnerException.ToString());
                }

                _logger.LogInformation("Salesforce Service running at: {time}", DateTimeOffset.Now);
                await Task.Delay(2500, stoppingToken);
            }
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Service Stop at: {time}", DateTimeOffset.Now);
            return base.StopAsync(cancellationToken);
        }

        public override void Dispose()
        {
            _logger.LogInformation("Resources released at: {time}", DateTimeOffset.Now);
            base.Dispose();
        }
    }

编辑

我现在已经使用 svc 正常安装了该服务,但我一直收到此错误

[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely fashion.

我设法解决了问题并在我的机器上本地部署了服务;事实证明包裹是分开的; Microsoft.AspNetCore.Hosting.WindowsServicesMicrosoft.Extensions.Hosting.WindowsServices

所以我所要做的就是添加包并重构 program.cs,如下所示;

public static void Main(string[] args)
        {

            CreateWebHostBuilder(args).Build().RunAsService();

        }

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1044);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });

有关更多上下文,请参阅此 link