Saturday, July 7, 2007

Adding custom behavior to your WCF service.

Sometime you may need custom service behavior, like you want to customized dispatch behavior or you want to put message inspector or even you want to redirect your service, you must need custom behavior. WCF offers lot of ways to add custom behavior; here I describe the easiest way to add custom service behavior. This is very simple things to do.
Steps:

1. You have to build a class implementing interface IServiceBehavior. This will describe your service behavior. More than one service behavior instance can work together.

2. You have to add this behavior to your service host, before open. Once you open your host, you cannot change service behavior.

Here is sample for typical service behavior class:

class CustomServiceBehavior : IServiceBehavior
{
#region IServiceBehavior Members

public void AddBindingParameters(ServiceDescription serviceDesc, ServiceHostBase serviceHostBase, Collection endpoints, BindingParameterCollection bindingParameters)
{
return;
}

public void ApplyDispatchBehavior(ServiceDescription serviceDesc, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
{
epDisp.DispatchRuntime.OperationSelector = new CustomDispatchOperationSelector();
// “CustomDispatchOperationSelector” my class which select dispatch operation.
epDisp.DispatchRuntime.InstanceProvider = new CustomServiceInstanceProvider();
// “CustomServiceInstanceProvider” a custom service provider class, which provide the instance for the service.
epDisp.DispatchRuntime.MessageInspectors.Add(new CustomMessageInspector());
// “CustomMessageInspector” is also a cutom class which inspect every message passes to this service.
foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations)
op.ParameterInspectors.Add(new CustomParameterInspector());
// “CustomParameterInspector” this is parameter inspector class which inspect each parameter for each message.
}
}
}

public void Validate(ServiceDescription serviceDesc, System.ServiceModel.ServiceHostBase serviceHostBase)
{
return;
}

#endregion
}

Now I add custom service behavior to my service at the main program where I start the service.

ServiceHost host = new ServiceHost(typeof(CustomService));
host.Description.Behaviors.Add(new CustomServiceBehavior ());
host.Open();
Console.WriteLine("Service Host is ready…");
Console.ReadKey();
host.Close();

// This is very simple code to add custom service behavior.

Custom service behavior is very important for customized service. It is better practice to customize your service host if you need extreme level of customization. But this is all you need to inspection your message.

Have fun with WCF...

No comments:

Post a Comment

Please, no abusive word, no spam.