经过一周的研究并尝试处理会话更改后,我仍然无法获得我正在寻找的结果。我查看了所有可用的示例,并彻底检查了TopShelf源代码。我的主要课程如下:
class Program
{
static void Main(string[] args)
{
//Always start out in our apps base directory
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
const string serviceName = "Service";
const string displayName = "Service";
const string description = "Provide assistance";
try
{
HostFactory.Run(x =>
{
x.UseCommonLogging();
x.UseNinject(new IocModule());
x.Service<ServService.Service.WinService>(sc =>
{
sc.WhenStarted((s, hostControl) => s.Start(hostControl));
sc.WhenStopped((s, hostControl) => s.Stop(hostControl));
sc.WhenSessionChanged((se, e, id) =>
{
se.SessionChange(e, id);
});
//sc.WhenSessionChanged((s, chg) => s.SessionChange(chg));
sc.ConstructUsingNinject();
});
x.EnableSessionChanged();
x.RunAsLocalSystem();
x.EnableServiceRecovery(r =>
{
r.RestartService(0);
});
x.StartAutomatically();
x.SetDescription(description);
x.SetDisplayName(displayName);
x.SetServiceName(serviceName);
这是我的服务类:
{
class WinService : ServiceControl
{
private CancellationTokenSource cancelSource;
private CancellationToken ct;
public ILog Log { get; private set; }
public WinService(ILog logger)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
}
public void SessionChange(SessionChangedArguments chg)
{
Log.Info("Service session changed!!!!!!!!!!!");
}
//Starts service
public bool Start(HostControl hostControl)
{
Console.Writeline("STARTED!);
return true;
}
//Stops service
public bool Stop(HostControl hostControl)
{
cancelSource.Cancel();
return true;
}
}
每次我运行代码时,无论发生任何更改,我都会打印出来自TopShelf源代码API WindowsServiceHost.cs
类的默认值,而不是
“[Topshelf]服务会话已更改”
但根据我的代码,它应该打印“服务会话已更改!!!!!!!!!!!” isntead。这是我所指的Top Shelf Source Code,相关的部分从第217行开始。任何帮助都会一如既往地受到赞赏。
答案 0 :(得分:2)
一个老问题,但是我能够使用我的IMyService类(和具体的)来触发我的事件,这个类是#34; standalone&#34;,也就是说,不会从microsoft或topshelf的任何服务基础继承
populate_queue(sub { $queue->enqueue(@_) });
我的具体:
public interface IMyServiceContract
{
void Start();
void Stop();
void SessionChanged(Topshelf.SessionChangedArguments args);
}
和我的&#34; program.cs&#34; main&#34;&#34;方法
public class MyService : IMyServiceContract
{
public void Start()
{
}
public void Stop()
{
}
public void SessionChanged(SessionChangedArguments e)
{
Console.WriteLine(e.ReasonCode);
}
}
如果您写入文本文件(我有Console.WriteLine(e.ReasonCode);)...您可以看到更改。我通过执行LockUser(在Windows 10 x64中)并重新登录来测试。
它为我工作。
我的packages.config让您知道哪个版本的TopShelf使用
IMyServiceContract myServiceObject = new MyService(); // // container.Resolve<IMyServiceContract>();
HostFactory.Run(x =>
{
x.Service<IMyServiceContract>(s =>
{
s.ConstructUsing(name => myServiceObject);
s.WhenStarted(myso => myso.Start());
s.WhenStopped(myso => myso.Stop());
s.WhenSessionChanged((myso, hc, chg) => myso.SessionChanged(chg));
});
x.EnableSessionChanged();