Service Host in WCF

Service Host :

Service implementation is just a .NET class, to have a runtime environment for it, so it can be executed somehow. That’s what the ServiceHost is for –

  • it will load your service class, set up the endpoints and channel listeners and all that stuff, and thus give your service class an “ecosystem” to live and operate in.

You can either instantiate a ServiceHost class yourself in a console app, a Windows service, or even a Winforms app, and thus make your WCF service class available to the outside world – or you can delegate that work to IIS or WAS. Even IIS or WAS will use a ServiceHost to host your WCF service – they just do it automagically behind the scenes, and “on demand” – whenever a request for your WCF service comes in.

//Creating uri for the hosting the service

Uri uri = new Uri(“http://localhost/CategoryService”);

//Creating the host object for MathService

ServiceHost host = new ServiceHost(typeof(CategoryService), uri);

//Adding endpoint to the Host object

host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri);

host.Open(); //Hosting the Service

Console.WriteLine(“Waiting for client invocations”);

Console.ReadLine();

host.Close();

Advertisements

ABC’s of WCF

Understanding the Basics of WCF:

Well, while developing the WCF Service, there should be place where we specify the Service URL, mode of connectivity & list of accessible functionality of that services.

This placeholder is Endpoint. So in the service program, we expose a collection of Endpoints. Each Endpoint is a portal for communicating with the client.

i mean when a cleint refers any service from thier application, these endpoints data gets loaded in thier application configuration file.

All the WCF communications are take place through end point. End point consists of three components.

Address : Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g http://localhost:8090/MyService/SimpleCalculator.svc

Binding : It will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements. A binding has several characteristics, including the following:

  •  Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  •  Encoding (Optional) – Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).

  • Protocol(Optional) – Defines information to be used in the binding such as Security, transaction or reliable messaging capability
Place to specify all binding types

Contract : Collection of operation that specifies what the endpoint will communicate with the client.Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client.Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

  • For Ex;

<system.serviceModel>

<services>

<service behaviorConfiguration=LoanServicingBehavior

name=eFinOffice.WebServer.SilverlightHost.LaonStagingService>

<endpoint address=“”

binding=basicHttpBinding

bindingConfiguration=basicHttpBinding_LoanServicing

contract=eFinOffice.WebServer.SilverlightHost.ILaonStagingService>

<identity>

<dns value=localhost />

</identity>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name=LoanServicingBehavior>

<serviceMetadata httpGetEnabled=true />

<dataContractSerializer maxItemsInObjectGraph=2147483647 />

<serviceDebug includeExceptionDetailInFaults=true />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

 

BehaviorConfiguration is a reference to a seperate section – ‘Service Behaviours’Now comes the “behaviorConfiguration” & “bindingConfiguration” && what are these & what for???

We can add “behaviorConfiguration” to Service tag, to specify further more configurations to service, ie..whether to allow MetaData to be published. This will essentially create a WSDL which describes the service.(<serviceMetadata httpGetEnabled=”true”/>)

BindingConfiguration is to add extra settings to binding. Ie MaxTime taken to bind, Max data allowed etc.

It is a also specified under seperate section – <Bindings>

ex: <bindingname=basicHttpBinding_Laon

closeTimeout=00:10:00

openTimeout=00:10:00

maxBufferSize=2147483647

maxReceivedMessageSize=2147483647

receiveTimeout=00:20:00

sendTimeout=00:20:00>

<readerQuotasmaxArrayLength=2147483647

maxStringContentLength=2147483647

maxDepth=2147483647

maxBytesPerRead=2147483647

maxNameTableCharCount=2147483647 />

</binding>

Contracts :

  • In WCF, all services are exposed as contracts.
  • Contract is a platform-neutral and standard way of describing what the service does.

Service Contract :

  • Service contracts describes the operation that service can provide
  • It is basically a interface which specifies all the operations that service can provide.Internaly operations has to be specified using OperationContract attribute to qualify as a service member.
  • This is been implemented by SVC file to define the concrete implementation of the operations.

Operation Contract : The operations exposed by the service has to be specified using this attribute.

Data Contract:

  • Data contract describes the custom data type which is exposed to the client. basically inputs & outputs to service.
  • Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.
  • So whoever DataContract is specified, be part of metadata in WSDL.

Message Contract:

  • Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
  • When we go for this???

Fault Contract :

  • Suppose there could be a exceptional scenario in a service side, i would like to throw a exception.But Exception should be a platform neutral. So when u throw a .net Exception, client may/may not be aware of the Exception. So in order to communicate the Exception to client, we go for Fault Contract.
  • Step 1: Create a Class which stores a exception details and ur are going to throw this to client. So this has to be attributed as Data Contract.
  • Step 2: Operation Contract which suppose to throw the Exception has to be specified with Fault Contract & has to specify the type of fault(this is the class which u throw)

Throw will be like (throw new FaultException(ex,”Reason: Testing the Fault contract”) 😉

  • Step 3: Since client knows the method with Fault Contract, and there they can Catch the exception using (FaultException<MyCalculatorService.CustomException>)

WCF Introduction

WCF :

  • Code named Indigo
  • programming platform and runtime system for building, configuring and deploying network-distributed services.
  • Interoperability is the fundamental characteristics of WCF
  • WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Advantages :

  • WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  • WCF services provide better reliability and security in compared to ASMX web services.
  • In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  • WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Development Tools

  • Microsoft Visual studio with Multi-targeting feature(You can create application in different framework like Framework 2.0, 3.0 and 3.5)
  • WCF – Test Client tools for testing the WCF service. Microsoft provides inbuilt application to test the WCF application. This can be done by opening the Visual Studio command prompt and type the wcftestClient.exe Serviceurl shows below. This will help the developer to test the service before creating the client application.
  • WCF services can be debugged. Wcfsvchost.exe will do it for you because service will be self hosted when you start debugging.

Difference between WCF and Web service:

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Dependency injection

What? Before knowing what is dependency injection, we’ll c what principles responsible for evolution of this. 1. Dependency inversion : this solid principle says, higher level layers should’nt depend upon direct concrete classes in lowlevel, instead depends upon abstraction. Why?? If higher level classes depends upon direct low level concrete classes, there might be changes comin up. The particular concrete class may be replaced by another similar concrete class which inherits same abstraction. So the rule says, coupling should be less. 2. Interface segregation : this solid principle says to increase the cohesion always, ie, the class should be holding single responsibility. Ie,if dependent layers expects an interface, it should not be forced to implement members which are not required becoz they are part of that fatty interface.instead one fatty interface can be segregated into relevant small interfaces, so that dependent classes can implement necessary interfaces. So above two principles implicitly says 1. Higher dependent layers expects a dependenclies from low level layers. 2. In order to exposing low level functionality, we expose abstraction mostly in the form of interfaces. 3. While exposing interfaces, we have to ensure relevant skinned interface is exposed. Dependency injection says, if any high level class depends on low level concrete class,since above principles enforces to dependent on skinned interface so here comes ways to get that reference abstract member. It’s all about ways of injecting that dependency. It’s of four types. 1. Constructor injection- can be done easily using mediatory class 2.method level injection- can be done easily using mediatory class 3.field level injection. can be done using reflection 4. Property injection. Can be done using reflection . For field and property, there are many ioc containers to inject the dependencies. Ioc refers to inverse of control. Few IOC Containers : ninject, spring, unity, seasor etc.

Difference btw implicit and explicit implemention of interfaces

When a class inherited from a interfaces, it has to implement that interface. So usually we go for implicit implementation.
Here question comes..then when do we go for explicit implementation ??
Cases:
1.when we inherit from more than an interface, which has common elements. Ie, with same signature.so in order to differentiate, we go for explicit implementation, where explicitly specify the interface name before elements.
2.when we want to restrict the access of interface members in implementing classes.