Single service handler with multiple contracts

9 בדצמבר 2008

תגיות: ,
אין תגובות

During the previous week Rami (my teammate) and I had an interesting problem. We had to develop two WCF services with some shared collection. One of the solutions we had was to store this collection as a static collection, and then each one of them will be able to get it. But we found a better solution. We created only one service handler class which implements the both contract interface at the same time. At the beginning we weren’t sure that this idea can be implemented, surprisingly it worked. As you probably know you can define several endpoints to the same service, each one of them with a different binding like this one:

<services>
<
service
behaviorConfiguration="WcfService.Service1Behavior"
name="WcfService.ServiceHandler">
<
endpoint
address="http://localhost:2010/ServiceHandler.svc"
binding="wsHttpBinding"
contract="WcfService.ICustomerService">
</
endpoint>
<
endpoint
address="net.tcp://localhost:2020/ServiceHandler.svc"
binding="netTcpBinding"
contract="WcfService.ICustomerService">
</
endpoint>
</
service>
</
services>

But our question was: Can we associate more than one contract to a single service?

So we created something like this:

<services>
<
service
behaviorConfiguration="WcfService.Service1Behavior"
name="WcfService.ServiceHandler">
<
endpoint
address="http://localhost:1056/ServiceHandler.svc"
binding="wsHttpBinding"
contract="WcfService.IOrderService">
</
endpoint>
<
endpoint
address="http://localhost:1056/ServiceHandler.svc"
binding="wsHttpBinding"
contract="WcfService.ICustomerService">
</
endpoint>
</
service>
</
services>

After few tests it worked. Now our service handler class looks like this:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ServiceHandler : IOrderService, ICustomerService
{

}

We added the InstanceServiceMode service behavior attribute with the “Single” value to define only one service handler class instance for the entire service requests. Now we have one service handler class which implements more than one service contract.

According to this idea you can work with inheritance interfaces too, for example assume you have this interface:

[ServiceContract]
public interface ICRM : ICustomerService, IOrderService
{
}

You can easily define only one service and get two in the same price.

I attached a code sample of it.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים