Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
can someone please help me with scenarios in which one would use multiple service contract in WCF service??

What I have tried:

I am new bee to WCF and seen the one example of multiple service contract in one service but not able to figure out the senarios in which one should use
C#
multiple service contract in one service
Posted
Updated 4-Dec-16 13:32pm

1 solution

If you have shared data between logically distinct sets of operations it is generally much easier to implement multiple contracts on a single service rather than implementing a custom ServiceHost which supports dependency injection. Especially if you are new to WCF. A common pattern is the use of partial classes like this:

C#
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
partial class DownloadService : IDownload
{
  //Various download function like Add, Remove, Start, Stop, etc. go here
}

partial class DownloadService : ISettings
{
  //Settings functions related to download functionality go here
}

[ServiceContract(SessionMode = SessionMode.Allowed)]
interface IDownload
{
  [OperationContract(IsOneWay = true)]
  void AddDownload(Download download);
  //Then whatever other functions to download you use
}

[ServiceContract(SessionMode = SessionMode.Allowed)]
interface ISettings
{
  [OperationContract(IsOneWay = true)]
  void SaveSettings();
  //Other functions for settings like Add, Remove, Load, etc.
}

[DataContract]
struct Download
{
  [DataMember]
  public string Name {get; private set;}
  [DataMember]
  public int Packet {get; private set;}
  public Download(string name, int packet)
  {
    Name = name;
    Packet = packet;
  }
}


So in this example this service is used to download from somewhere. You also want various settings that let you control how the DownloadService functions. Well, this is obviously going to require some shared data between the settings and DownloadService. A quick and easy way to go about that is simply to wrap up both functionalities into a single service and expose multiple contracts - one for downloading and one for settings. A more advanced solution that's more in line with SOLID[^] principles would be to derive your own ServiceHost class which injects the shared dependency into service instances. I have a tip/trick here[^] that can show you how to accomplish this but I'd stick to simple solutions while learning :)

Hope this helped!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900