Thursday, August 4, 2011

It took me around 10 working hours to know me how to host a WCF service in a Windows service. It took a long time but I am able to do it. I am describing the steps below, let me know if I am wrong somewhere. Open Visual Studio 2010 and Click on File -> New Project -> Go to the WCF project template and then select WCF Service Library. Just to let you know that I am not sure what will happen when you will select WCF Service Application over WCF Service Library. I have choosen WCF Service Library here. Need to check the difference :) as shown in fig.


The project contains one App.config file, Iservice1.cs file and Service1.cs file. You can
write your code in the Service1.cs file. I added a simple method to this class as below.
In the IService1.cs add
 [OperationContract]
 string GetName(string firstName, string lastName); Refer figure below:


inside the interface. And implement the method in the Service1.cs as below. Also you can check the figure below.
  public string GetName(string firstName, string lastName)
        {
            return firstName + " " + lastName;
        }


Then change the App.config file which is very much important. Change the things as below:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WcfTestLib.Service1"
behaviorConfiguration="WcfTestLib.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "net.tcp://localhost:8732/Design_Time_Addresses/WcfTestLib/Service1"/>
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <endpoint name="NetTcpEndPoint" address ="" binding="netTcpBinding"
contract="WcfTestLib.IService1"/>
        <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
        <!--<identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>-->
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint name="NetTcpMetadataPoint" address="mex"
binding="mexTcpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfTestLib.Service1Behavior">
          <!-- To avoid disclosing metadata information,
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false"/>
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
Remember this step is very important. so be careful while changing the baseAddress, endpoint and serviceBehaviors. Now our WCF service work finished. 


Now we need to create a window service that will host the WCF service. For this go to the Solution right click on it. Add new project and select Windows service from there. Then your windows service project will appear in the solution explorer. Here first we need to give two references. First one is the WCF project that we have made first. For this click on Refernces -> Add Referencce and select the project section by visiting the project section from the reference window. And then Give reference to the System.ServiceModel namespace from the .Net section in the Add Reference window.


After the reference work complete, Copy the App.config file from the WCF project and Paste it in the Window service project. Here no need to change anything.
In the next step right click on the Service1.cs file and click on view code section. We have to override the OnStart () and OnStop() methods. First give reference to using System.ServiceModel;
Then write ServiceHost myHost = null; in the class and override the methods as follows.
        protected override void OnStart(string[] args)
        {
            myHost = new ServiceHost(typeof(WcfTestLib.Service1));
            myHost.Open();
        }
Here one thing to remember is that the typeof contains WcfTestLib which is my WCF library project.
        protected override void OnStop()
        {
            myHost.Close();
        }
The full code will look as below.
In the next step open the Service1.cs designer page Right click and Add Installer. From there you select serviceInstaller1 and select F4. And in the properties  You can give the display name that will appear in the list of services in the control pannel. Also you can select the start type. See the figure below.
Then click on the serviceProcessInstaller1 and click on F4. And in the properties window change the Account to NetworkService as shown in the figure below. 
Now you can rebuild the project and our windows service is ready to install. You can install it by using the command InstallUtil.exe but I am here going to describe how you can install by creating a set up project.
To create a set up project go to the solution explorer, right click on it then Add new project then select other porject types -> then Setup and Deployment and then Visual Studio Installer and the Select Setup project template as shown in the figure below.
Then right click on the set up project and Add -> Project output as shown in the figure below. 
The from the Add project output group window select your Window service project and select Primary output and click on ok as shown in the figure below.
Then right click on it and select View-> Custom actions as shown below.
Then right click on Custom Actions and click on Add custom action and click on Application folder in the Select Item in Project window and select the primary output. The final window will appear like below figure.


Now you code is ready to install and then you can go to the debug folder of the setup project and click on setup.exe or setup.msi it will install the service. And to check write services.msc in the Run window and clcik on ok. And from the list of services you can check the service.
To check whether its working or not you can write an separate windows application and then in the reference part click on Add service reference and in the Address winod give the base address URL like
net.tcp://localhost:8732/Design_Time_Addresses/WcfTestLib/Service1/mex or you can copy the URL from the
App.config file. If the service is working then you can get result like 1 service found. Hope will be helpful to you !!!
I have the sample project you can contact me or you can mail me on my mail id fewlines4biju@gmail.com for the sample project.

0 Comments:

Post a Comment