What is WCF?
Windows Communication Foundation API allows to build distributed architecture in such manner that once created, service code can be utilized by the in-house application which using tcp/ip to communicate, web application using http protocol to communicate to web services, application using msmq. WCF Services also works with the application developed other than .NET Framework.
Create WCF Service
Follow the below listed step to create Service.
Step 1
Create service from Visual Studio. Select the go to C# or VB, then select project type WCF Service library or WCF service website project template.
The first one creates the *.dll and app.config file after the compilation which you can then use in your host application and expose the service to clients.
The second one creates the project with the proper web.config file and *.svc file which gets hosted on IIS via virtual directly and service gets exposed to client via HTTP protocol. So by that service cannot be exposed to Tclient
. The benefit of this option is that there is no need to create host application you can directly host on IIS via virtual directory. For this discussion, first I am creating a WCF service library and then I am going to discuss about IIS deployment also.
Step 2
Create contract by specifying proper attributes. This contract tells the client what are the methods that get exposed by the service and custom type exposed by the service. You can decorate your contract by the list of attributes in System.ServiceModel
namespace. You can create your own files or after selecting proper project type, it creates two files for your Iservice.cs and Service.cs. If you are going to create your own files, it's recommended that you can create your interface and implement it in your class.
[ServiceContract]
- defines the interface to participate in provided service.
[ServiceContract]
public interface IService1
{
....
}
[OperationContract]
- defines the method going to be exposed by the service.
[OperationContract]
string GetData(int value);
[DataMember]
- defines the property exposed via service.
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataContract]
- defines the custom data type exposed via service.
[DataContract]
public class CompositeType
{
...
}
After you are done with the creation of the web service, your code should look as below.
Library app.config file
This file contains information about the metadata exchange defining endpoint of metadata. It also contains information about the endpoints where client talks with service. Endpoints are ABC means Address, Binding and Contract. As you see in the above config file service exposed for TCP communication by the following line:
<system.serviceModel>
<services>
<service name="WcfServiceLibrary.Service1"
behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8080/Service1/" />
</baseAddresses>
</host>
<endpoint address="net.tcp://localhost:9000/myservice"
binding="netTcpBinding" contract="WcfServiceLibrary.IService1">
</endpoint>
<endpoint address ="" binding="wsHttpBinding"
contract="WcfServiceLibrary.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfServiceLibrary.Service1Behavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Binding details: http://www.c-sharpcorner.com/UploadFile/pjthesedays/bindwcf05032009012251AM/bindwcf.aspx.
IService.Cs file
namespace WcfServiceLibrary
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}
Service.cs
namespace WcfServiceLibrary
{
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}
Hosting WCF Service
- Self Host
- IIS hosting
- Windows service
- WAS
Demo of Self hosting and IIS hosting.
Self Hosting
Step 1
Create new project >> Class Library >> name this project as Host.
Step 2
Add reference to the host application. Right click on Reference >> Add Reference.
Step 3
After adding reference to the host application to expose webservice for client to consume as you see below line of the code creates the object of the host and which is of type Service1
which we created in the WCF Service library project:
using (System.ServiceModel.ServiceHost host =
new System.ServiceModel.ServiceHost(typeof(Service1)))
{
}
As you can see, we used using
block over so that it disposes host object when we close application.
Step 4
To start the service to handle request coming from the client of their service, you need to call open
method:
host.Open();
and to stop receiving request, you need to call close
method.
Host.cs
namespace HostApp
{
class Program
{
static void Main(string[] args)
{
using (System.ServiceModel.ServiceHost host =
new System.ServiceModel.ServiceHost(typeof(Service1)))
{
host.Open();
Console.WriteLine("Service started. press any key to stop it");
Console.ReadLine();
host.Close();
}
}
}
}
IIS Hosting
- To host same WCF library in your application, create WCF Web application project using WCF web application template as we discuss in start.
- Delete the files created in the IService.cs and Service.cs file from App_Code folder
- Include WCF library *.dll file which we created.
- Open Service.svc file and modify the single line in it.
<xmlns="http://www.w3.org/1999/xhtml"><xmlns="http://www.w3.org/1999/xhtml">
<%@ ServiceHost Language="C#" Debug="true"
Service="WcfServiceLibrary.Service1" %>
Change the web service WEB.Config file to expose service to client, i.e., you need to create same element as listed above in the app.config file of service library.
Consuming WCF Service
Step 1
Create new project >> Class Library >> name this project as Client as we created Host application. If you want to consume webservice hosted in your web application, start directly for the 2 step listed below.
Step 2
Add Service Reference to the client by Right clicking on project >> Add Service Reference.
which automatically creates the proxy files to consume web service, or make use of ServiceModel Metadata Utility Tool (Svcutil.exe), the command-line tool to generate proxy code from metadata.
svcutil /t:code http://<service_url> /out:<file_name>.cs /config:<file_name>.config
Step 3
To send request to service from the client:
ServiceReference1.Service1Client client = new Client.ServiceReference1.Service1Client();
Console.WriteLine(client.GetData(5));
Console.ReadLine();
client.Close();
So, as you see in the above code, you need to create object of Service1Client
and then you can easily call the method exposed by the Service
. If you want to see the auto-generated code, press F12 on the Service1Client
which shows the proxy code to you.
Summary
As you follow the process listed step by step, it's quite easy to create, consume and host WCF Service.