我目前正在使用ASP.NET和WebHostBuilder在Windows中托管一个WebHost (.NET 5)应用程序。
.NET 6引入了WebApplication和WebApplicationBuilder。如何使用这些在Windows服务中进行主机?
发布于 2022-01-06 02:17:31
您可以使用这里记录的UseWindowsService()扩展方法:
与以前的版本一样,您需要安装Microsoft.Extensions.Hosting.WindowsServices NuGet包。
在.NET 6中用WebApplicationBuilder实现这一点需要一个解决办法:
var webApplicationOptions = new WebApplicationOptions() { ContentRootPath = AppContext.BaseDirectory, Args = args, ApplicationName = System.Diagnostics.Process.GetCurrentProcess().ProcessName };
var builder = WebApplication.CreateBuilder(webApplicationOptions);
builder.Host.UseWindowsService();更新的
微软已经改变了应该如何创建服务,作为解决这个问题的方法。--contentRoot参数应该与exe一起使用。
sc config MyWebAppServiceTest binPath= "$pwd\WebApplication560.exe --contentRoot $pwd\"New-Service -Name {SERVICE NAME} -BinaryPathName "{EXE FILE PATH} --contentRoot {EXE FOLDER PATH}" -Credential "{DOMAIN OR COMPUTER NAME\USER}" -Description "{DESCRIPTION}" -DisplayName "{DISPLAY NAME}" -StartupType Automatic发布于 2022-08-05 23:52:16
我有一个现有的控制台应用程序,它只运行针对Microsoft.Extensions.Hosting.IHostedService 6的.Net实现,并且希望添加一个在服务运行时可用的web接口。我想这就是你要做的。
步骤
Sdk属性
新程序类
using MyWindowsService.App;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
// Create the builder from the WebApplication but don't call built yet
var appBuilder = WebApplication.CreateBuilder(args);
// Add the windows service class as a HostedService to the service collection on the builder
appBuilder.Services.AddHostedService<MyWindowsService>();
// Build the builder to get a web application we can map endpoints to
var app = appBuilder.Build();
// Map an endpoint
app.MapGet("/", () => "Hello World!");
// Run the web application
app.Run();旧程序类
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyWindowsService.App
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyWindowsService>();
});
}
}
}https://stackoverflow.com/questions/70571849
复制相似问题