1
我正在使用Topshelf運行我的wcf服務和Windsor城堡以進行依賴注入。當我直接運行主機程序時出現問題,它作爲控制檯主機運行良好,但同一程序在嘗試將其作爲Windows服務啓動時出現此錯誤。使用頂級架子和溫莎城堡的主機WCF服務
Topshelf.Hosts.StartHost Error: 0 : The service failed to start., System.Invalid
OperationException: Cannot start service MyService on computer '.'. ---> Sy
stem.ComponentModel.Win32Exception: The service did not respond to the start or
control request in a timely fashion
--- End of inner exception stack trace ---
at System.ServiceProcess.ServiceController.Start(String[] args)
at System.ServiceProcess.ServiceController.Start()
at Topshelf.Runtime.Windows.WindowsHostEnvironment.StartService(String servic
eName, TimeSpan startTimeOut)
at Topshelf.Hosts.StartHost.Run()
下面是我的實現: -
class Program{
static void Main(string[] args)
{
var boot = new ServiceInstaller();
HostFactory.Run(x =>
{
x.Service<Program>(s =>
{
s.ConstructUsing(name => new Program());
s.WhenStarted(p => p.Start());
s.WhenStopped(p => p.Stop());
});
x.DependsOnMsSql();
x.StartAutomatically();
x.SetDisplayName("My Service");
x.SetServiceName("MyService");
});
}
public void Start()
{
try
{
_serviceProvider = typeof(IMyService).AssemblyQualifiedName;
LogMessage(LogLevel.INFO, _serviceProvider, null);
if (_serviceProvider == null)
{
throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, "Failed to start service: {0}", _serviceProvider));
}
_serviceHost = new DefaultServiceHostFactory().CreateServiceHost(_serviceProvider, new Uri[0]);
_serviceHost.Open();
}
catch (Exception ex)
{
LogMessage(LogLevel.ERROR, "Error occurred while starting My Service", ex);
throw;
}
}
public void Stop()
{
try
{
_serviceHost.Close();
_serviceHost = null;
}
catch (Exception ex)
{
LogMessage(LogLevel.ERROR, "Error occurred while stopping My service ", ex);
throw;
}
}
}
public Class ServiceInstaller{
public static IWindsorContainer Container { get; private set; }
public ServiceInstaller()
{
try
{
Container = new WindsorContainer();
Container.Register(Component.For<IWindsorContainer>().Instance(Container));
Container.AddFacility<WcfFacility>().Register
(
Component.For<IDependency>().ImplementedBy<Dependency>().LifestyleTransient(),
Component.For<IMyService>().ImplementedBy<MyService>().LifestyleTransient()
);
}
catch (Exception ex)
{
throw;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Container != null)
{
Container.Dispose();
Container = null;
}
}
}
}
可能在Start中的代碼在作爲服務運行時引發異常。嘗試在每條語句之後和第一條語句之前放置一條日誌消息,以查看哪條線路正在拋出。 – Marwijn 2015-03-02 10:33:09
這可能是真的,但它爲什麼運行良好時,通過Visual Studio進行調試或只是在bin文件夾中運行它。 – Pijush 2015-03-02 10:36:46
您是否檢查過Windows事件日誌以查看是否在那裏記錄異常? – RagtimeWilly 2015-03-02 10:41:23