Thursday, March 8, 2012

WCF Behaviour Indepth

A behavior is a special type of class that extends runtime behavior during the ServiceHost/ChannelFactory initialization process.

Eg: In wcf sessions there is an attribute called InstanceContextMode and this is a behaviour(applied to service).

Behaviour could also be applied to operations. Infact there are four types of behaviors: service, endpoint, contract, and operation as given in this table:


as we can see each type of behavior is also modeled by a different interface definition, but they all share the same set of methods

One thing to note is that IServiceBehavior doesn't have an ApplyClientBehavior method because service behaviors can't be applied to clients. Which also means other three behaviours can be applied to both clients and services.

As a WCF developer where all could you implement or deal with Behaviour?
1) Configuration
2) Code(C#)
3) Reflection/Powershell(not discussed here)

Configration:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="OurBehavior">
<serviceMetadata httpGetEnabled="True" />
</behavior>
code(C#)
ServiceDiscoveryBehavior discoveryBehavior = new ServiceDiscoveryBehavior();
host.Description.Behaviours.Add(discoveryBehavior);

There is also a [CallbackBehavior]
Use the CallbackBehaviorAttribute attribute to configure or extend the execution behavior of a callback contract implementation in a client application(duplex). Eg:-

one use of Callbackbehaviour: if the client is a windows form and gets multiple call back calls and processing these call backs might block main UI thread. To prevent this you should do the following,
decorate the client call back with CallbackBehavior attrib. UseSynchronizationContext = false, Concurrenymode = concurrencymode.multiple and UseSynchronizationContext=false as given below.

[CallbackBehaviorAttribute(
  IncludeExceptionDetailInFaults= true,
  UseSynchronizationContext=false,
  ConcurrenyMode =ConcurrencyMode.Multiple
)]
public class Client : SampleDuplexHelloCallback

....
}

An alternative to this solution is to use the Background worker when making calls to the service. This will run outside the WinForms Synchronization context and allow incoming calls to run without blocking.
-End- please comment your thoughts

No comments:

Post a Comment