Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Proxy Class to Common Interface with WCF Services

Tags:

.net

wcf

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)

like image 528
Blake Blackwell Avatar asked Nov 23 '25 00:11

Blake Blackwell


1 Answers

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();
  }
like image 197
Patrick Avatar answered Nov 25 '25 15:11

Patrick