WCF Interview Question & Answer

What is WCF?

Microsoft refers WCF as a programming platform that is used to build Service-oriented applications. Windows Communication Foundation is basically a unified programming model for developing, configuring and deploying distributed services.  Microsoft has unified all its existing distributed application technologies (e.g. MS Enterprise Services, ASMX web services, MSMQ, .NET Remoting etc) at one platform i.e. WCF. Code name for WCF was Indigo.

Why to use WCF? or What are the advantages for using WCF?

  • Service Orientation is one of the key advantages of WCF. We can easily build service-oriented applications using WCF.
  • If compared with ASMX web services, WCF service provides reliability and security with simplicity.
  • As oppose to .NET Remoting, WCF services are interoperable.
  • Different clients can interact with same service using different communication mechanism. This is achieved by using service endpoints. A single WCF service can have multiple endpoints. So, developer will write code for service once and just by changing configuration (defining another service endpoint), it will be available for other clients as well.
  • Extensibility is another key advantage of WCF.  We can easily customize a service behavior if required.
What are the core components of WCF Service?
A WCF service has at least following core components.
  • Service Class:  A ervice class implementing in any CLR-based language and expose at least one method.
  • Hosting Environment: a managed process for running service.
  • Endpoint: a client uses it to communicate with service.

What is the difference between WCF and ASMX Web services?

The basic difference is that ASMX web service is designed to send and receive messages using SOAP over HTTP only. While WCF service can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc).

What are the Endpoints in WCF? or Explain ABCs of endpoint?

For WCF services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role.
A service endpoint has three basic elements or also called ABCs of an endpoint i.e. Address, Binding and Contract.
Address: It defines “WHERE”. Address is the URL that identifies the location of the service.
Binding: It defines “HOW”. Binding defines how the service can be accessed.
Contract: It defines “WHAT”. Contract identifies what is exposed by the service.

What is a WCF Binding? How many different types of bindings available in WCF?

Bindings in WCF actually defines that how to communicate with the service. Binding specifies that what communication protocol as well as encoding method will be used. Optionally, binding can specify other important factors like transactions, reliable sessions and security.
Another WCF Tutorial gives more detailed understanding of Binding concept in WCF.
There are different built-in bindings available in WCF, each designed to fulfill some specific need.
  • basicHttpBinding
  • wsHttpBinding
  • netNamedPipeBinding
  • netTcpBinding
  • netPeerTcpBinding
  • netmsmqBinding
For details on different binding types, please follow the link to WCF bindings.

Can we have multiple endpoints for different binding types in order to serve different types of clients?

Yes, we can have multiple endpoints for different binding types. For example, an endpoint with wsHttpBinding and another one with netTcpBinging.

What are the hosting options for WCF Services? Explain.

For a service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  • Hosting in a Managed Application/ Self Hosting
    • Console Application
    • Windows Application
    • Windows Service
  • Hosting on Web Server
    • IIS 6.0 (ASP.NET Application supports only HTTP)
    • Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
      NamedPipes, MSMQ.

What are Contracts in WCF?

A Contract is basically an agreement between the two parties i.e. Service and Client. In WCF, Contracts can be categorized as behavioral or structural.
  1. Behavioral Contracts define that what operations client canperform on a service.
    • ServiceContract attribute is used to mark a type as Service contract that contains operations.
    • OperationContract attributes is used to mark the operations that will be exposed.
    • Fault Contract defines what errors are raised by the service being exposed.
  2. Structural Contracts
    • DataContract  attribute define types that will be moved between the parties.
    • MessageContract attribute define the structure of SOAP message.

What Message Exchange Patterns supported by WCF?

  •  Request/Response
  •  One Way
  •  Duplex
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios.If we want queued message delivery, OneWay is the only available option.
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.
Next WCF Tutorial on Interview Questions and Answers in this series is about Proxy and Channel Factory, Concurrency and Throttling in WCF.

What are the different ways to expose WCF Metadata?

By default, WCF doesn’t expose metadata. We can expose it by choosing one of the following ways:
1.    In configuration file, by enabling metadata exchange as follows:
           <service name=”MyService.Service1″
                      <endpoint address=””
                              <dns value=”localhost”/>
                     <endpoint address=”mex” binding=”mexHttpBinding”
                        <behavior name=”MyService.Service1″>
                                    <serviceMetadata httpGetEnabled=”true”/>
                                    <serviceDebug includeExceptionDetailInFaults=”false”/>
2.  ServiceHost can expose a metadata exchange endpoint to access metadata at runtime.
   using (ServiceHost host = new ServiceHost(typeof(MyService)))
              ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
              behavior.HttpGetEnabled = true;
              Console.WriteLine(“My Service here……….”);              Console.ReadLine();

What is mexHttpBinding in WCF?

In order to generate proxy, we need service metadata and mexHttpBinding returns service metadata.
If we look into our configuration file, service will have an endpoint with mexHttpBinding as follows:
<endpoint address=”mex” binding=”mexHttpBinding”   contract=”IMetadataExchange”/>
and service metadata behavior will be configured as follows:
<serviceMetadata httpGetEnabled=”true”/>
Before deployment of application to production machine, it should be disabled.
In order to support other protocols, related bindings are mexHttpBinding, mexHttpsBinding, mexTcpBinding.

What is a Service Proxy in Windows Communication Foundation?

A service proxy or simply proxy in WCF enables application(s) to interact with WCF Service by sending and receiving messages. It’s basically a class that encapsulates service details i.e. service path, service implementation technology, platform and communication protocol etc. It contains all the methods of service contract (signature only, not the implementation). So, when the application interact the service through proxy, it gives the impression that it’s communicating a local object.
We can create proxy for a service by using Visual Studio or SvcUtil.exe.

What are the different ways to generate proxy in WCF?

Generating proxy using Visual Studio is simple and straight forward.
  • Right click References and choose “Add Service Reference”.
  • Provide base address of the service on “Add Service Reference” dialog box and click “Go” button. Service will be listed below.
  • Provide namespace and click OK.
Visual studio will generate a proxy automatically.
We can generate proxy using svcutil.exe utility using command line. This utility requires few parameters like HTTP-GET address or the metadata exchange endpoint address and a proxy filename i.e. optional.
svcutil http://localhost/MyService/Service1.svc /out:MyServiceProxy.cs
If we are hosting the service at a different port(other than default for IIS which is 80), we need to provide port number in base address.
svcutil http://localhost:8080/MyService/Service1.svc /out:MyServiceProxy.cs
For parameter details regarding svcutil, please follow the MSDN link

Difference between using ChannelFactory and Proxies in WCF?

A ChannelFactory creates a kind of Channel used by clients to communicate with service endpoints.
If we have control over Server and Client, then ChannelFactory is a good option because it relies on having local interfaces that actually describes the service i.e. service contract.
On the other hand, If we don’t have control over server and only have WSDL/URL, then it’s better to generate proxy using Visual Studio or SvcUtil.
SvcUtil is better option as compared to Visual Studio because we have more control in case of SvcUtil.

How to create proxy for Non-WCF Services?

In case of Non-WCF Services, we can create proxy by either using Visual Studio or svcUtil.exe tool by pointing to WSDL of the non-WCF service. In this scenario, we can’t create proxy through ChannelFactory or manually developing proxy class because we don’t have local interfaces i.e. service contract.

Breifly explain Automatic Activation in WCF?

Automatic activation means service starts and serves the request when a message request is received, but service doesn’t need to be running in advance.
There are few scenarios in which service needs to be running in advance, For example, in case of Self-Hosting.

What are the different WCF Instance Activation Methods available?

WCF supports three different types of Instance Activation methods:
a)    Per Call
b)    Per Session
c)    Singleton

What are the different ways to handle concurrency in WCF?

There are three different ways to handle concurrency in WCF that are:
a)    Single
b)    Multiple
c)    Reentrant
Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served.
Multiple: means multiple requests can be served by multiple threads of a single WCF service instance.
Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service.
We can apply these concurrency settings by putting ConcurrencyMode property in ServiceBehavior as follows:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple]
public class MyService : IMyService

What is WCF throttling?

WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions. Basic purpose is to control our WCF service performance by using Service throttling behavior.
In configuration file we can set this behavior as follows:
        <behavior name=”MyServiceBehavior”>
Above given values are the default ones, but we can update it after looking into the requirements of our application.

What is a fault contract?

Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.”
 public interface IService1
        int MyOperation1();
  public class MyFaultDetails
        public string ErrorDetails { get; set; }
In implementing service…..
  public int MyOperation1()
       Try{               //Do something……       }catch()
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);

A user has a service with a one-way operation that includes a fault contract, and he gets an exception when he tries to host the service. Why?

This is true, because, to return faults, the service requires some form of a two-way communication channel, which is not there with one-way operations.

What are the core security concepts supported by WCF?

There are four core security Features
Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client.
Integrity: is to ensure that message received is not being tempered or changed during exchange.
Authentication: is a way for the parties (sender and receiver) to identify each other.
Authorization: ensures that what actions an authenticated user can perform?

Difference between Message Level security and Transport Level security?

Security can be configured at different levels in Windows Communication Foundation.
  1. Transport Level Security
  2. Message Level Security

    Difference between BasicHttpBinding and WsHttpBinding with respect to security?

    Please follow differences between BasicHttpBinding and WsHttpBinding for more detailed discussion, but basic difference with respect to security is as follows:
    As WsHttpBinding supports advanced WS-* specification, it has a lot more security options available. For example, It provides message-level security i.e. message is not sent in plain text. Also it supports for WS-Trust and WS-Secure conversation.
    While in case of BasicHttpBinding, it has fewer security options, or we can say, there is no security provided, by default. At transport level, it can provide confidentiality through SSL.

    Please explain about authorization options supported in WCF?

    Authorization as a core feature of security in WCF supports different authorization types.
    Role-based authorization is the most common authorization approach being used. In this approach, authenticated user has assigned roles and system checks and verifies that either a specific assigned role can perform the operation requested.
    Identity-based authorization approach basically provides support for identity model feature which is considered to be an extension to role-based authorization option. In this approach, service verifies client claims against authorization policies and accordingly grant or deny access to operation or resource.
    Resource-based authorization approach is a bit different because it’s applied on individual resources and secure those using windows access control lists (ACLs).

    What is Reliable Messaging in WCF?

    We know that networks are not perfect enough and those might drop signals or in some scenarios there can be a possibility of wrong order of messages during message exchange.
    WCF allows us to ensure the reliability of messaging by implementing WS-ReliableMessaging protocol.  Here is how you can configure reliable messaging in WCF.
        <binding name=”Binding1″>
                                            inactivityTimeout=”00:02:00″ />

    What are Reliable Sessions in WCF?

    Reliable sessions actually ensure that the caller for messages will know about the lost message(s) but it can’t guarantee about the delivery of message(s).
    There is a misconception about reliable sessions that it ensures the session will never expire or stays for a very long time. This we can achieve by using timeout for sessions.

    Briefly explain WCF RESTfull services?

    RESTful services are those which follow the REST (Representational State Transfer) architectural style.As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, NamedPipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But Http is much more than just a transport.
    So, when we talk about REST architectural style, it dictates that “Instead of using complex mechanisms like CORBA, RPC or SOAP for communication, simply HTTP should be used for making calls”.
    RESTful architecture use HTTP for all CRUD operations like (Read/CREATE/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE). It’s simple as well as lightweight.
    You can follow 5 simple steps to create your first RESTful service.

    Briefly explain WCF Data Services?

    WCF Data services previously known as ADO.NET data services are basically based on oData (Open Data Protocol) standard which is a REST (Representational State Transfer) protocol. According to http://www.odata.org/
    The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients and servers in a variety of products over the past several years.  OData is being used to expose and access information from a variety of sources including, but not limited to, relational databases, file systems, content management systems and traditional Web sites.Next part in this WCF Tutorial series is focused on Interview Questions regarding Service-Oriented Architecture and Transactions.

    What is SOA (Service Oriented Architecture) and how WCF supports it?

    SOA is basically an architectural model that dictates few principles for building business applications in the form of independent, loosely coupled and interoperable services. These services are well defined, self-contained and can work together to achieve certain business functionality without depending on context or state of other services.
    WCF supports almost all those principles dictated by Service Oriented Architecture for developing services; those are independent, loosely coupled and interoperable also. Please visit for detailed discussion on WCF and SOA.

    What is ESB in SOA environment?

    In Service Oriented Architecture environment, ESB (Enterprise Service Bus) acts as a single interface for all messaging between applications and services in a loosely coupled manner. ESB is capable to call and subscribe different service provider’s methods and subscriptions respectively.

    What is Transaction Propagation? And how WCF support it?

    Transaction propagation is the ability to propagate transaction across the boundaries of a single service. Or in other words, we can say that a service can participate in a transaction that is initiated by a client.
    In a SOA environment, transaction propagation becomes a key requirement. As we know that WCF supports SOA, so it provides support for transaction propagation as well.
    To enable transaction propagation, we need to set the value of TransactionFlow property of the binding being used. This can be done programmatically as follows:
      WSHttpBinding bindingBeingUsed = new WSHttpBinding();
      bindingBeingUsed.TransactionFlow = “true”;
     Or It can be done declaratively by updating configuration file as follows:
                   <binding name=”binding1”
                                       transactionFlow=”true” />

Does all WCF bindings support for Transaction Propagation?

No. Not all WCF bindings support transaction propagation. Only following list of bindings support for it.
  • wsHttpBinding
  • netTcpBinding
  • netNamedPipeBinding
  • wsDualHttpBinding
  • wsFederationHttpBinding

What are the various Transaction Flow Options available in WCF?

If a service is configured for Transaction Propagation, WCF further supports various options for service methods to be part of any transaction initiated outside service boundaries.
  • NotAllowed Transaction Propagation is not allowed for particular service method. Its default value.
  • Allowed Transaction Propagation is allowed but not compulsory.
  • Mandatory Transaction Propagation is compulsory for that service method.
For example, Transaction Propagation is mandatory for CreditAccount service method in following code snippet.
   interface IPaymentService
              void CreditAccount(….);

What is two-phase committed protocol?

In a distributed transaction scenario, two-phase committed protocol is an algorithm that ensures all the participating processes in a distributed transaction are ready to be committed or roll backed. This is done in two phases i.e. Prepare phase and Commit phase.

What is the role of transaction manager in WCF?

Transaction manager while sitting on client side, initiate the transaction and coordinates with all the processes that participate in a distributed transaction to commit or roll back.

What are the supported transaction types in WCF?

Supported transaction types in WCF are:
  • Light Weight
  • OLE Transactions
  • WS-Atomic Transactions

How to enable the Performance Counters in WCF?

Simple way to enable Performance Counters supported by WCF is as follows:
                 <diagnostics performanceCounters = “All” />
Above configuration setting will enable all categories of counters including ServiceModelService, ServiceModelEndpoint and ServiceModelOperation. Default value for it is “Off”.

3 techniques for Instance management in WCF

Instance management basically defines the binding of service instance to a request received from a client. In case of WCF, following three techniques for service instantiation are available: 

  • PerCall
  • PerSession
  • Single
As we know that application requirements varies from one to another with respect to scalability, durability, performance, transactions etc, so in order to meet respective needs of the application, we chose between different WCF service instance modes and this is what we are going to discuss here in this WCF Tutorial.

“PerSession” is the default instance mode for WCF Service. In order to use any specific techniques mentioned above, we need to configure serviceBehavior attribute for a service as follows:
public interface IInstanceManagDemoService
string Method1();
public class InstanceManagDemoService : IInstanceManagDemoService
public string Method1()
//method details here…..
In case of PerCall Instance mode, a new instance is created against each request coming from client and later disposed off when response is sent back from service as shown in the following diagram.

Above diagram shows that all request coming from one or more clients are served by separate instance on server. 
Key points about this approach are follows:
  • We will prefer to use this approach when we don’t need to maintain state between requests.
  • Scalability is a major concern and service holds expensive resources like communication ports, files or database connections etc.
For PerSession Instance mode, a new instance is maintained on server for one session. For separate session, another instance is created that serves the request. Normally, we use this technique, when we need to maintain session between multiple requests.
Above diagram shows that for all requests from “WCF Client 1″ are served by “Service Instance 1″. Same is the case for client 2 and client 3 respectively. In this technique, the service instance is disposed off when one a particular client completes its all method calls to perform a specific functionality.

Key points about this approach are follows:
  • Approach is preferable when we need to maintain state.
  • Scalability is a concern but not the biggest concern.
In case of Single/Singleton Instance mode, only one instance is created to serve all the requests coming from all clients.
In this technique, service instance is not disposed off and it stays on server to serve all incoming requests.
Key points about this approach are follows:
  • We want to share global data using service.
  • Scalability is not a concern at all.

4 simple steps to enable tracing in WCF 


 Tracing mechanism in Windows Communication Foundation is based on the classes that resides in System.Diagnostic namespace. Important classes are Trace, TraceSource and TraceListener. For better understanding we will follow step by step approach in this WCF Tutorial. Following are the steps to enable tracing in WCF:

Step 1. Configuring WCF to emit tracing information/Define Trace Source

We have the following options:
  • System.ServiceModel
  • System.ServiceModel.MessageLogging
  • System.ServiceModel.IdentityModel
  • System.ServiceModel.Activation
  • System.Runtime.Serialization
  • System.IO.Log
  • Cardspace
In configuration file, we will define a source to enable this configuration as follows:
      <source name=”System.ServiceModel.MessageLogging”> 

Step 2. Setting Tracing Level

We have the following available options, we need to set this tracing level to available options other than default “Off”:
  • Off
  • Critical
  • Error
  • Warning
  • Information
  • Verbose
  • ActivityTracing
  • All
In configuration file, we can choose above values for switchValue attribute as follows:
<source name=”System.ServiceModel.MessageLogging”

Step 3. Configuring a trace listener

For configuring a trace listener, we will add following to config file.
<add name=”messages”
initializeData=”d:logsmessages.svclog” />

Step 4. Enabling message logging

logEntireMessage: By default, only the message header is logged but if we set it to true, entire message including message header as well as body will be logged.
logMalformedMessages: this option log messages those are rejected by WCF stack at any stage are known as malformed messages.
logMessagesAtServiceLevel: messages those are about to enter or leave user code.
logMessagesAtTransportLevel: messages those are about to encode or decode.
maxMessagesToLog: maximum quota for messages. Default value is 10000.
maxSizeOfMessageToLog: message size in bytes.
Putting all this together, configuration file will appear like this.
      <source name=”System.ServiceModel.MessageLogging”>
          <add name=”messagelistener”
               type=”System.Diagnostics.XmlWriterTraceListener” initializeData=”d:logsmyMessages.svclog”></add>
        <messageLogging logEntireMessage=”true”
Note: In this case, information will be buffered and not published to file automatically, So, we can set the autoflush property of the trace under sources as follows:
autoflush =”true” />