我使用以下示例创建了一个ASP.NET Core Windows Service应用程序:https://github.com/dotnet/AspNetCore.Docs/tree/master/aspnetcore/host-and-deploy/windows-service/samples/2.x/AspNetCoreService
现在,我想使用命令行安装我的服务,比如"MyService.exe -install“。我知道如果我使用"sc create“将会工作,但我想安装使用我自己的应用程序来安装和配置我想要的服务。
我找到了一个使用Toshelf包的示例,但我使用的是WebHostBuilder,并且我尝试使用自定义服务配置。服务已安装,但当我启动它时,它不工作。
我使用的是.NET Core2.2。
我的配置:
HostFactory.Run(x =>
{
x.Service<CustomWebHostService>(sc =>
{
sc.ConstructUsing(() => new CustomWebHostService(host));
// the start and stop methods for the service
sc.WhenStarted(ServiceBase.Run);
sc.WhenStopped(s => s.Stop());
});
x.RunAsLocalSystem();
x.StartAutomatically();
x.SetServiceName("Teste Core");
x.SetDisplayName("Teste ASP.NET Core Service");
x.SetDescription("Teste ASP.NET Core as Windows Service.");
});我的完整源代码:https://github.com/rkiguti/dotnetcore.windows-service
发布于 2020-07-17 22:35:26
我像另一个示例一样更改了代码,我的服务现在作为控制台应用程序和windows服务运行。它可以使用命令行"MyService.exe install“来安装。
我的program.cs文件:
class Program
{
public static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<ApplicationHost>(sc =>
{
sc.ConstructUsing(() => new ApplicationHost());
// the start and stop methods for the service
sc.WhenStarted((svc, control) =>
{
svc.Start(control is ConsoleRunHost, args);
return true;
});
sc.WhenStopped(s => s.Stop());
sc.WhenShutdown(s => s.Stop());
});
x.UseNLog();
x.RunAsLocalSystem();
x.StartAutomatically();
x.SetServiceName("Test Core");
x.SetDisplayName("Test ASP.NET Core Service");
x.SetDescription("Test ASP.NET Core as Windows Service.");
});
}
}我的ApplicationHost.cs文件:
public class ApplicationHost
{
private IWebHost _webHost;
public void Start(bool launchedFromConsole, string[] args)
{
if (!launchedFromConsole)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot);
}
IWebHostBuilder webHostBuilder = CreateWebHostBuilder(args);
_webHost = webHostBuilder.Build();
_webHost.Start();
// print information to console
if (launchedFromConsole)
{
var serverAddresses = _webHost.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
foreach (var address in serverAddresses ?? Array.Empty<string>())
{
Console.WriteLine($"Listening on: {address}");
Console.WriteLine("Press Ctrl+C to end the application.");
}
}
}
public void Stop()
{
_webHost?.Dispose();
}
private IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddEventLog();
})
.ConfigureAppConfiguration((context, config) =>
{
// Configure the app here.
})
.UseUrls("http://+:8000")
.UseStartup<Startup>();
}完整的源代码:https://github.com/rkiguti/dotnetcore.windows-service
https://stackoverflow.com/questions/62877853
复制相似问题