tags:

views:

80

answers:

2

I am trying to create a common service library shared between a WCF web service and a local data service. However, when trying to utilize the service by clicking on

Project -> Add Service Reference

and then trying to use the base interface instead of the proxy interface I get a cast error with the following code:

IMyService _context = (IMyService)new ServiceReference.MyService();

Here is a layout of the projects / classes:

Common Library Project

[ServiceContract]
public interface IMyService
{
     [OperationContract]
     void DoWork();
}

Web Service Project

public partial class MyService : IMyService
{
    public void DoWork()
    {
    //DO STUFF
    }
}

Client Project

IMyService _context = (IMyService)new ServiceReference.MyService();

runtime error thrown: Can't cast object.

IMyService _context = new ServiceReference.MyService();

compile time error thrown: Explicit cast is missing.

(note that Client Project references Common Library Project)

A: 

You should not cast it as the returned class implements the interface, simply remove the cast.

Ben Robinson
I originally tried it without a cast, but I get a compile error that states at an explicit conversion exists. Any other thoughts?
Blake Blackwell
+1  A: 

If you control both sides of the wire, you could also generate a dynamic proxy through code. You could work without the generated proxy via add web reference. For my company this works better as changes in the interface will directly show during compilation on our build server. When we used web references these interface breaks would show up during testing of our application.

This is what we use to generate the proxy dynamically. Maybe this could also work for your scenario.

  private void CreateDynamicProxy()
  {
     var endPoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(TServerInterface)), new BasicHttpBinding(), new EndpointAddress(EndpointAddress));
     var channelFactory = new ChannelFactory<IMyInterface>(endPoint);
     IMyInterface myInterface = channelFactory.CreateChannel();
     myInterface.MyMethod();
     ((IChannel) myInterface).Close();
  }
kalkie
This appears to be just what I needed. I need to look into it some more, but I was able to get a simple prototype up and running with your code. Thanks!
Blake Blackwell