NetCore 2.1 通用主机即服务



我正在尝试使用最新的Dotnet Core 2.1运行时构建Windows服务。我没有托管任何 aspnet,我不想也不需要它来响应 http 请求。

我遵循了示例中的代码:https://github.com/aspnet/Docs/tree/master/aspnetcore/fundamentals/host/generic-host/samples/2.x/GenericHostSample

我也读过这篇文章:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-2.1

使用 dotnet run 在控制台窗口中运行时,代码效果很好。 我需要它作为Windows服务运行。 我知道有Microsoft.AspNetCore.Hosting.WindowsServices,但那是针对WebHost的,而不是通用主机。 我们会使用主机。RunAsService(( 作为服务运行,但我在任何地方都没有看到它的存在。

如何将其配置为作为服务运行?

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MyNamespace
{
public class Program
{

public static async Task Main(string[] args)
{
try
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
configHost.SetBasePath(Directory.GetCurrentDirectory());
configHost.AddJsonFile("hostsettings.json", optional: true);
configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configHost.AddCommandLine(args);
})
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.AddJsonFile("appsettings.json", optional: true);
configApp.AddJsonFile(
$"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
optional: true);
configApp.AddEnvironmentVariables(prefix: "ASPNETCORE_");
configApp.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
services.AddLogging();
services.AddHostedService<TimedHostedService>();
})
.ConfigureLogging((hostContext, configLogging) =>
{
configLogging.AddConsole();
configLogging.AddDebug();
})
.Build();
await host.RunAsync();
}
catch (Exception ex)
{

}
}

}
#region snippet1
internal class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Timed Background Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
#endregion
}

编辑:我再说一遍,这不是托管 ASP.NET 核心应用程序。 这是一个通用的主机构建器,而不是WebHostBuilder。

正如其他人所说,您只需要重用用于IWebHost接口的代码,这里有一个例子。

public class GenericServiceHost : ServiceBase
{
private IHost _host;
private bool _stopRequestedByWindows;
public GenericServiceHost(IHost host)
{
_host = host ?? throw new ArgumentNullException(nameof(host));
}
protected sealed override void OnStart(string[] args)
{
OnStarting(args);
_host
.Services
.GetRequiredService<IApplicationLifetime>()
.ApplicationStopped
.Register(() =>
{
if (!_stopRequestedByWindows)
{
Stop();
}
});
_host.Start();
OnStarted();
}
protected sealed override void OnStop()
{
_stopRequestedByWindows = true;
OnStopping();
try
{
_host.StopAsync().GetAwaiter().GetResult();
}
finally
{
_host.Dispose();
OnStopped();
}
}
protected virtual void OnStarting(string[] args) { }
protected virtual void OnStarted() { }
protected virtual void OnStopping() { }
protected virtual void OnStopped() { }
}
public static class GenericHostWindowsServiceExtensions
{
public static void RunAsService(this IHost host)
{
var hostService = new GenericServiceHost(host);
ServiceBase.Run(hostService);
}
}

我希望你找到了这个问题的解决方案。

就我而言,我为此目的使用了通用主机(在 2.1 中引入(,然后只需将其与 systemd 包装在一起即可在 Linux 主机上作为服务运行。

我写了一篇关于它的小文章 https://dejanstojanovic.net/aspnet/2018/june/clean-service-stop-on-linux-with-net-core-21/

我希望这有帮助

IHostedService如果是 [asp.net core] 后端作业, 如果要在 .NET Core 上构建 Windows 服务,则应引用此包 System.ServiceProcess.ServiceController,并使用ServiceBase作为基类。 (您也可以从 .NET Framework Windows 服务开始,然后更改.csproj文件(


编辑:请参阅此文档和此代码 https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNetCore.Hosting.WindowsServices/WebHostWindowsServiceExtensions.cs。 创建用于管理IHost的 Windows 服务ServiceBase

最新更新