Jak zrobić a.NET uruchomienie usługi Windows zaraz po instalacji?
Poza serwisem.StartType = ServiceStartMode.Automatyczna moja usługa nie uruchamia się po instalacji
Rozwiązanie
Wstawiłem ten kod do mojego ProjectInstaller
protected override void OnAfterInstall(System.Collections.IDictionary savedState)
{
base.OnAfterInstall(savedState);
using (var serviceController = new ServiceController(this.serviceInstaller1.ServiceName, Environment.MachineName))
serviceController.Start();
}
Dzięki ScottTx i Francisowi B.]} 8 answers
Możesz to zrobić z poziomu pliku wykonywalnego usługi w odpowiedzi na zdarzenia wywołane przez proces InstallUtil. Nadpisuje Zdarzenie OnAfterInstall, aby użyć klasy ServiceController do uruchomienia usługi.
Http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-28 17:42:13
Opublikowałem krok po kroku procedurę tworzenia usługi Windows w C# tutaj . Wygląda na to, że jesteś przynajmniej do tego momentu, a teraz zastanawiasz się, jak uruchomić usługę po jej zainstalowaniu. Ustawienie właściwości StartType na automatyczny spowoduje, że usługa uruchomi się automatycznie po ponownym uruchomieniu systemu, ale (jak już zauważyłeś)nie uruchomi się automatycznie po instalacji.
Nie pamiętam gdzie go znalazłem (być może Marc Gravell?), ale znalazłem rozwiązanie online, które pozwala zainstalować i uruchomić usługę, faktycznie uruchamiając samą usługę. Oto krok po kroku:
-
Uporządkuj
Main()
funkcję swojego serwisu tak:static void Main(string[] args) { if (args.Length == 0) { // Run your service normally. ServiceBase[] ServicesToRun = new ServiceBase[] {new YourService()}; ServiceBase.Run(ServicesToRun); } else if (args.Length == 1) { switch (args[0]) { case "-install": InstallService(); StartService(); break; case "-uninstall": StopService(); UninstallService(); break; default: throw new NotImplementedException(); } } }
-
Oto kod wspierający:
using System.Collections; using System.Configuration.Install; using System.ServiceProcess; private static bool IsInstalled() { using (ServiceController controller = new ServiceController("YourServiceName")) { try { ServiceControllerStatus status = controller.Status; } catch { return false; } return true; } } private static bool IsRunning() { using (ServiceController controller = new ServiceController("YourServiceName")) { if (!IsInstalled()) return false; return (controller.Status == ServiceControllerStatus.Running); } } private static AssemblyInstaller GetInstaller() { AssemblyInstaller installer = new AssemblyInstaller( typeof(YourServiceType).Assembly, null); installer.UseNewContext = true; return installer; }
-
Kontynuując kod wspierający...
private static void InstallService() { if (IsInstalled()) return; try { using (AssemblyInstaller installer = GetInstaller()) { IDictionary state = new Hashtable(); try { installer.Install(state); installer.Commit(state); } catch { try { installer.Rollback(state); } catch { } throw; } } } catch { throw; } } private static void UninstallService() { if ( !IsInstalled() ) return; try { using ( AssemblyInstaller installer = GetInstaller() ) { IDictionary state = new Hashtable(); try { installer.Uninstall( state ); } catch { throw; } } } catch { throw; } } private static void StartService() { if ( !IsInstalled() ) return; using (ServiceController controller = new ServiceController("YourServiceName")) { try { if ( controller.Status != ServiceControllerStatus.Running ) { controller.Start(); controller.WaitForStatus( ServiceControllerStatus.Running, TimeSpan.FromSeconds( 10 ) ); } } catch { throw; } } } private static void StopService() { if ( !IsInstalled() ) return; using ( ServiceController controller = new ServiceController("YourServiceName")) { try { if ( controller.Status != ServiceControllerStatus.Stopped ) { controller.Stop(); controller.WaitForStatus( ServiceControllerStatus.Stopped, TimeSpan.FromSeconds( 10 ) ); } } catch { throw; } } }
W tym momencie, po zainstalowaniu usługi na docelowej maszynie, wystarczy uruchomić usługę z wiersz poleceń (jak każda zwykła aplikacja) z argumentem linii poleceń
-install
, Aby zainstalować i uruchomić usługę.
Myślę, że omówiłem wszystko, ale jeśli okaże się, że to nie działa, proszę dać mi znać, abym mógł zaktualizować odpowiedź.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:17
Visual Studio
Jeśli tworzysz projekt instalacyjny z VS, możesz utworzyć niestandardową akcję, która wywołała metodę. NET, aby uruchomić usługę. Nie zaleca się jednak używania managed custom action W MSI. Zobacz tę stronę .
ServiceController controller = new ServiceController();
controller.MachineName = "";//The machine where the service is installed;
controller.ServiceName = "";//The name of your service installed in Windows Services;
controller.Start();
InstallShield lub Wise
Jeśli używasz InstallShield lub Wise, te aplikacje zapewniają opcję uruchomienia usługi. Na przykład z Wise, musisz dodać akcję kontroli usługi. W tym akcja, określasz, czy chcesz uruchomić lub zatrzymać usługę.
Wix
Używając Wix musisz dodać następujący kod xml w komponencie swojej usługi. Aby uzyskać więcej informacji na ten temat, Możesz sprawdzić tę stronę .
<ServiceInstall
Id="ServiceInstaller"
Type="ownProcess"
Vital="yes"
Name=""
DisplayName=""
Description=""
Start="auto"
Account="LocalSystem"
ErrorControl="ignore"
Interactive="no">
<ServiceDependency Id="????"/> ///Add any dependancy to your service
</ServiceInstall>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-28 17:43:39
Musisz dodać niestandardową akcję na końcu sekwencji 'ExecuteImmediate' w MSI, używając nazwy komponentu EXE lub partii (SC start) jako źródła. Nie sądzę, że można to zrobić za pomocą Visual Studio, być może będziesz musiał użyć do tego prawdziwego narzędzia do tworzenia MSI.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-28 17:20:26
Aby uruchomić go zaraz po instalacji, generuję plik wsadowy z installutil a następnie SC start
To nie jest idealne, ale działa....
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-28 17:20:22
Użyj klasy. NET ServiceController, aby ją uruchomić, lub wydaj polecenie wiersza poleceń, aby ją uruchomić - - - "net start servicename". Tak czy siak działa.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-28 17:21:11
Aby dodać do odpowiedzi ScottTx, oto rzeczywisty kod do uruchomienia usługi, jeśli robisz to Microsoft way (ie. korzystanie z projektu instalacji itp...)
(excuse the VB.net kod, ale to jest to, z czym utknąłem)
Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
Dim sc As New ServiceController()
sc.ServiceName = ServiceInstaller1.ServiceName
If sc.Status = ServiceControllerStatus.Stopped Then
Try
' Start the service, and wait until its status is "Running".
sc.Start()
sc.WaitForStatus(ServiceControllerStatus.Running)
' TODO: log status of service here: sc.Status
Catch ex As Exception
' TODO: log an error here: "Could not start service: ex.Message"
Throw
End Try
End If
End Sub
Aby utworzyć powyższą obsługę zdarzeń, przejdź do projektanta ProjectInstaller, gdzie znajdują się 2 kontrolki. Kliknij na kontrolkę ServiceInstaller1. Przejdź do okna właściwości w obszarze zdarzenia i tam znajdziesz Zdarzenie AfterInstall.
Uwaga: Nie umieść powyższy kod w zdarzeniu AfterInstall dla ServiceProcessInstaller1. To nie zadziała, z doświadczenia. :)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-27 17:18:47
Najprostsze rozwiązanie znajdziesz tutaj install-windows-service-without-installutil-exe by @ Hoàng Long
@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"
echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:31