Niraj Bhatt – Architect's Blog

Ruminations on .NET, Architecture & Design

Explicit Interface Implementation and WCF

You are inheriting from 2 contracts to create a contract. Both contracts that you are inheriting from have a method with same name and signature. You don’t have much control over these interfaces as they are tightly coupled with your subsystem. You create an implementation class with help of explicit interface implementations and dispatch calls to subsystem. Now you have a challenge of invoking the right implementation from client side? Will WCF work even when we can’t have any config files? Fortunately YES, WCF supports such scenarios. Below is a code sample on same, hope it helps you when you have a sharp knife against your throat 🙂 :

//Contracts
[ServiceContract]
public interface IIPV4Location
{
[OperationContract]
string GetLocationId();
}

[ServiceContract]
public interface IIPV6Location
{
[OperationContract(Name = "IIPV6Location")] //A must for WCF to distinguish
string GetLocationId();
}

[ServiceContract]
public interface ILocation : IIPV4Location, IIPV6Location
{ }

//Server Side
class LocationImpl : ILocation
{
string IIPV4Location.GetLocationId()
{
return "Ipv4";
}

string IIPV6Location.GetLocationId()
{
return "Ipv6";
}
}

class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(LocationImpl), new Uri("http://localhost:9999/"));
var behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(behavior);

host.AddServiceEndpoint(typeof(ILocation), new BasicHttpBinding(), "Location");

host.Open();
Console.WriteLine("Running...");
Console.ReadLine();
host.Close();
}
}

//Client Side
class Program
{
static void Main(string[] args)
{
ILocation location = new ChannelFactory(new BasicHttpBinding(),
"http://localhost:9999/Location")
.CreateChannel();

var ipv4Location = ((IIPV4Location)location).GetLocationId();
Console.WriteLine(ipv4Location);

var ipv6Location = ((IIPV6Location)location).GetLocationId();
Console.WriteLine(ipv6Location);
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: