browse by category or date

WCF Service Library

WCF Service Library project will generate only the .dll file. Below is the structure of brand new WCF Service Library project:

│   App.config
│   IService1.cs
│   Service1.cs
│   WcfServiceLibrary1.csproj
│
├───bin
│   └───Debug
├───obj
│   └───Debug
│       │   .NETFramework,Version=v4.7.2.AssemblyAttributes.cs
│       │   DesignTimeResolveAssemblyReferencesInput.cache
│       │
│       └───TempPE
└───Properties
        AssemblyInfo.cs

Since it is only generating .dll, how will it be served? This is where things get interesting. We can use:

  1. IIS. We just need to create the web.config and service.svc files like a typical WCF Service Application.
    web.config
    <?xml version="1.0"?>
    <configuration>
    
      <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.7.2" />
        <httpRuntime targetFramework="4.7.2"/>
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
              
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <!-- To browse web app root directory during debugging, set the value below to true.  
              Set to false before deployment to avoid disclosing web app folder information. -->      
        <directoryBrowse enabled="true"/>
      </system.webServer>
    
    </configuration>
    
    
    service.svc
    <%@ ServiceHost 
    	Language="C#" 
    	Debug="true" 
    	Service="WcfServiceLibrary1.Service1" 
    	CodeBehind="Service1.svc.cs" %>
    

    Then create a structure similar to WCF Service Application:

    │   service.svc
    │   web.config
    │
    └───bin
            WcfServiceLibrary1.dll
    
  2. Self-Hosting. Self-hosting means we will manage the program which hosts the service ourself. This means we can use any WCF transport protocol. Let’s start with a simple .NET Console program to host WCF service.
    Program.cs
    using System;
    using System.ServiceModel;
    using WcfServiceLibrary1;
    
    namespace WCFHost
    {
        class Program
        {
            static void Main(string[] args)
            { 
                using (ServiceHost host = new ServiceHost(typeof(Service1)))
                {
                    host.Open();
    
                    Console.Write("Host Open");
                    Console.ReadLine();
                    Console.WriteLine("Host closing down");
                }
            }
        }
    }
    
    App.config
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
      </startup>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior name="Service1Behavior">
              
              <serviceMetadata httpGetEnabled="true"/>
    
              
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <services>
          <service name="WcfServiceLibrary1.Service1" behaviorConfiguration="Service1Behavior"> 
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:20000"/>
              </baseAddresses>
            </host> 
          </service>
    
        </services>
      </system.serviceModel>
    </configuration>
    

    Since we are hosting http other than port 80, we need to run process as Administrator, otherwise we will have this error:

    Unhandled Exception: System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:20000/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---> System.Net.HttpListenerException: Access is denied
       at System.Net.HttpListener.AddAllPrefixes()
       at System.Net.HttpListener.Start()
       at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
       --- End of inner exception stack trace ---
       at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
       at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
       at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
       at System.ServiceModel.Channels.TransportChannelListener.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.HttpChannelListener`1.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
       at System.ServiceModel.Channels.CommunicationObject.Open()
       at WCFHost.Program.Main(String[] args) in D:\Projects\wcf\WCFHost\Program.cs:line 13
    

    Instead of running as Administrator everytime, we can reserve the port using the following command (must run command prompt as Administrator):

    netsh http add urlacl url=http://+:20000/ user=$MachineOrDomain\$UserName
    

    Remember to replace $MachineOrDomain and $UserName with your actual credential.

    After we run the host program, we should be able to view the service in the browser:

    We should be able to consume the service by adding service reference to the client program.

That’s it for now. Hopefully by now, we should be able to differentiate between WCF Service project, WCF Service Application project and WCF Service Library project.

I hope it helps. Cheers!

GD Star Rating
loading...
The Difference Between WCF Service, WCF Service Application and WCF Service Library (Part 3), 3.0 out of 5 based on 1 rating

Possibly relevant:

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

Incoming Search

.net, c#, wcf

No Comment

Add Your Comment