Я создаю сервис Windows, используя. net core 3.1 с Topshelf и Serilog. Serilog работает нормально, если я запускаю только exe. Если я запускаю как службу с «MyServiceApp.exe start», то создается файл журнала и записывается некоторый начальный журнал. Но это все. Ничего от MyService!
2020-03-18 13:38:33.389 +01:00 [INF] Args: ["start"]
2020-03-18 13:38:33.452 +01:00 [INF] Configuration Result:
[Success] Name MyService
[Success] Description MyService.
[Success] ServiceName MyService
2020-03-18 13:38:33.458 +01:00 [INF] Topshelf v4.2.1.215, .NET Framework v3.1.0
2020-03-18 13:38:33.474 +01:00 [DBG] Starting MyService
2020-03-18 13:38:34.226 +01:00 [INF] The MyService service was started.
Program.cs:
var exeRootFolder = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
var configuration = new ConfigurationBuilder()
.SetBasePath(exeRootFolder)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
HostFactory.Run(windowsService =>
{
windowsService.UseSerilog(Log.Logger);
windowsService.Service<RabbitMQServiceAgent>(sc =>
{
sc.ConstructUsing(hs => new MyService());
sc.WhenStarted((s, h) => s.Start(h));
sc.WhenStopped((s, h) => s.Stop(h));
});
windowsService.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));
windowsService.SetServiceName("MyService");
windowsService.SetDisplayName("MyService");
windowsService.SetDescription("MyService.");
});
MyService.cs
public class MyService : ServiceControl
{
public MyService()
{
}
public bool Start(HostControl hostControl)
{
Log.Information("Starting Service");
var myThread = new System.Threading.Thread(new System.Threading.ThreadStart(foreverWhile));
myThread.IsBackground = true;
myThread.Start();
return true;
}
public void foreverWhile()
{
while (true)
{
// to do something forever
Log.Debug("foreverWhile");
System.Threading.Thread.Sleep(2000);
}
}
public bool Stop(HostControl hostControl)
{
Log.Information("Stopping Service");
return true;
}
}
}