How to host WCF service in a Windows Service

How to host WCF service in a Windows Service

To host a WCF (Windows Communication Foundation) service in a Windows Service, you need to create a new Windows Service project and then configure and host the WCF service within it. Here's a step-by-step guide on how to achieve this:

Step 1: Create a new Windows Service project:

  • Open Visual Studio and create a new project.
  • Select "Windows Service" template under "Visual C# > .NET Framework" category.
  • Provide a name for your Windows Service project and click "Create."

Step 2: Implement the Windows Service:

  • In the newly created Windows Service project, you will find a Service1.cs file. Rename it to something more meaningful (e.g., MyWindowsService.cs).
  • Open the file and implement the OnStart and OnStop methods. These methods will be called when the service starts and stops, respectively.
using System.ServiceProcess; public partial class MyWindowsService : ServiceBase { private ServiceHost myServiceHost; public MyWindowsService() { InitializeComponent(); } protected override void OnStart(string[] args) { // Start the WCF service when the Windows Service starts myServiceHost = new ServiceHost(typeof(MyWcfService)); myServiceHost.Open(); } protected override void OnStop() { // Stop the WCF service when the Windows Service stops myServiceHost.Close(); } } 

Step 3: Implement the WCF service:

  • Create a new WCF service project (e.g., "WcfServiceLibrary") or use an existing one.
  • Implement your WCF service with its contracts, data contracts, and service implementation.
using System.ServiceModel; [ServiceContract] public interface IMyWcfService { [OperationContract] string GetData(int value); } public class MyWcfService : IMyWcfService { public string GetData(int value) { return "You entered: " + value; } } 

Step 4: Reference the WCF service project:

  • In your Windows Service project, add a reference to the WCF service project that you implemented in Step 3.

Step 5: Configure the service in the app.config:

  • In the Windows Service project, add a new "Application Configuration File" (app.config) if it's not already present.
  • Configure the WCF service in the app.config. This includes specifying the service behavior, bindings, and endpoints.
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="MyNamespace.MyWcfService" behaviorConfiguration="MyServiceBehavior"> <endpoint address="http://localhost:8000/MyWcfService" binding="basicHttpBinding" contract="MyNamespace.IMyWcfService"/> <host> <baseAddresses> <add baseAddress="http://localhost:8000/"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> 

Step 6: Install the Windows Service:

  • Build your Windows Service project in Release mode.
  • Open a Command Prompt as Administrator and navigate to the bin/Release folder of your Windows Service project.
  • Install the service using the installutil tool:
installutil MyWindowsService.exe 

Step 7: Start and control the service:

  • Open the "Services" window on your computer (Press Win+R, type services.msc, and press Enter).
  • Find your installed service (e.g., "My Windows Service") and start it.

Now, your WCF service should be hosted and running as a Windows Service. You can also control it (start, stop, restart) using the "Services" window. Clients can connect to your WCF service using the configured endpoint (e.g., http://localhost:8000/MyWcfService).

Examples

  1. Using ServiceBase Class:

    public class MyWindowsService : ServiceBase { private ServiceHost _serviceHost = null; public MyWindowsService() { InitializeComponent(); } protected override void OnStart(string[] args) { _serviceHost?.Close(); _serviceHost = new ServiceHost(typeof(MyWcfService)); _serviceHost.Open(); } protected override void OnStop() { _serviceHost?.Close(); _serviceHost = null; } } 

    Description: This code defines a Windows service that hosts a WCF service (MyWcfService) and starts the service when the Windows service starts.

  2. Using Configuration File:

    <system.serviceModel> <services> <service name="MyNamespace.MyWcfService"> <endpoint address="" binding="basicHttpBinding" contract="MyNamespace.IMyWcfService"/> </service> </services> </system.serviceModel> 

    Description: This configuration in the App.config or Web.config file defines the WCF service to be hosted by the Windows service.

  3. Using ServiceInstaller and ServiceProcessInstaller:

    [RunInstaller(true)] public class ProjectInstaller : Installer { public ProjectInstaller() { var serviceProcessInstaller = new ServiceProcessInstaller(); var serviceInstaller = new ServiceInstaller(); serviceProcessInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "MyWindowsService"; serviceInstaller.DisplayName = "My Windows Service"; serviceInstaller.Description = "Hosts MyWcfService as a Windows service."; Installers.Add(serviceProcessInstaller); Installers.Add(serviceInstaller); } } 

    Description: This code defines the installer for the Windows service, specifying the service name, display name, description, and service account.

  4. Using ServiceController Class:

    using (ServiceController serviceController = new ServiceController("MyWindowsService")) { serviceController.Start(); } 

    Description: This code programmatically starts the Windows service hosting the WCF service using the ServiceController class.

  5. Using Topshelf Library:

    class Program { static void Main(string[] args) { HostFactory.Run(x => { x.Service<MyWindowsService>(s => { s.ConstructUsing(name => new MyWindowsService()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetServiceName("MyWindowsService"); x.SetDisplayName("My Windows Service"); x.SetDescription("Hosts MyWcfService as a Windows service."); }); } } 

    Description: This code uses the Topshelf library to simplify the creation of a Windows service, including hosting a WCF service.

  6. Using OnCustomCommand Method:

    protected override void OnCustomCommand(int command) { if (command == 128) { // Start service OnStart(null); } else if (command == 129) { // Stop service OnStop(); } } 

    Description: This method allows the service to respond to custom commands, such as starting or stopping the hosted WCF service.

  7. Using Service Behavior Configuration:

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class MyWcfService : IMyWcfService { // Implementation of WCF service methods } 

    Description: By specifying the InstanceContextMode.Single attribute, this code ensures that only one instance of the WCF service is created and used throughout the lifetime of the Windows service.

  8. Using Self-Hosted WCF Service:

    protected override void OnStart(string[] args) { _serviceHost = new ServiceHost(typeof(MyWcfService)); _serviceHost.Open(); } 

    Description: This code snippet shows how to create and open a self-hosted WCF service instance within the Windows service.

  9. Using EventLog Integration:

    protected override void OnStart(string[] args) { if (!EventLog.SourceExists("MyService")) EventLog.CreateEventSource("MyService", "MyServiceLog"); eventLog.Source = "MyService"; eventLog.Log = "MyServiceLog"; eventLog.WriteEntry("My Windows Service started.", EventLogEntryType.Information); } 

    Description: This code initializes and writes log entries to the Windows Event Log when the service starts.

  10. Using WCF Service Configuration:

    <system.serviceModel> <services> <service name="MyNamespace.MyWcfService"> <endpoint address="" binding="basicHttpBinding" contract="MyNamespace.IMyWcfService"/> </service> </services> </system.serviceModel> 

    Description: This XML configuration snippet defines the WCF service within the Windows service, specifying the service name, endpoint address, binding, and contract.


More Tags

angular webcam-capture listener leap-year paging python-3.x rgb errno genymotion window-resize

More C# Questions

More Date and Time Calculators

More Biochemistry Calculators

More Auto Calculators

More Other animals Calculators