설치 직후 .NET Windows 서비스를 시작하는 방법은 무엇입니까?
service.StartType = ServiceStartMode.Automatic 외에 설치 후 내 서비스가 시작되지 않습니다.
해결책
내 ProjectInstaller에이 코드를 삽입했습니다.
protected override void OnAfterInstall(System.Collections.IDictionary savedState)
{
base.OnAfterInstall(savedState);
using (var serviceController = new ServiceController(this.serviceInstaller1.ServiceName, Environment.MachineName))
serviceController.Start();
}
ScottTx와 Francis B.
InstallUtil 프로세스에서 발생한 이벤트에 대한 응답으로 서비스 실행 파일 내에서이 모든 작업을 수행 할 수 있습니다. ServiceController 클래스를 사용하여 서비스를 시작하려면 OnAfterInstall 이벤트를 재정의하십시오.
http://msdn.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller.aspx
여기 에 C #에서 Windows 서비스를 만드는 단계별 절차를 게시했습니다 . 적어도이 시점까지 들리는 것 같고 이제 서비스가 설치되면 시작하는 방법이 궁금합니다. StartType 속성을 Automatic으로 설정하면 시스템을 재부팅 한 후 서비스가 자동으로 시작되지만 설치 후 서비스가 자동으로 시작되지는 않습니다.
원래 어디서 찾았는지 기억 나지 않지만 (아마도 Marc Gravell?) 실제로 서비스 자체를 실행하여 서비스를 설치하고 시작할 수있는 솔루션을 온라인에서 찾았습니다. 다음은 단계별입니다.
구조
Main()
같은 서비스의 기능을 :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(); } } }
다음은 지원 코드입니다.
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; }
지원 코드 계속 ...
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; } } }
At this point, after you install your service on the target machine, just run your service from the command line (like any ordinary application) with the
-install
command line argument to install and start your service.
I think I've covered everything, but if you find this doesn't work, please let me know so I can update the answer.
Visual Studio
If you are creating a setup project with VS, you can create a custom action who called a .NET method to start the service. But, it is not really recommended to use managed custom action in a MSI. See this page.
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 or Wise
If you are using InstallShield or Wise, these applications provide the option to start the service. Per example with Wise, you have to add a service control action. In this action, you specify if you want to start or stop the service.
Wix
Using Wix you need to add the following xml code under the component of your service. For more information about that, you can check this page.
<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>
You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.
To start it right after installation, I generate a batch file with installutil followed by sc start
It's not ideal, but it works....
Use the .NET ServiceController class to start it, or issue the commandline command to start it --- "net start servicename". Either way works.
To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)
(excuse the VB.net code, but this is what I'm stuck with)
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
To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.
Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)
The easiest solution is found here 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
'code' 카테고리의 다른 글
CleanWPPAllFilesInSingleFolder 오류로 인해 프로젝트가 더 이상로드되지 않습니다. (0) | 2020.09.13 |
---|---|
VueJs 2.0의 형제 구성 요소 간 통신 (0) | 2020.09.13 |
Objective-C는 C #과 어떻게 다릅니 까? (0) | 2020.09.13 |
로컬 네트워크의 장치에서 webpack-dev-server에 액세스하는 방법은 무엇입니까? (0) | 2020.09.13 |
오버레이 이미지에서 마우스 상호 작용 무시 (0) | 2020.09.13 |