user1164630
user1164630

Reputation: 1

Switching multiple classes to WCF

I have an interface and multiple classes using that interface, also on the server there's a factory that creates a specific instance based on some parameters.

Now I'd have to expose those classes to WCF clients, I hoped that I'd be able to mark the interface as OperationContract and establish the communication, but it seems that on the server (I'm new to WCF) I have to create a service (or at least open a port) per class and I can't do that for an interface.

Is that the only way to do it or am I missing something?

Edit to clarify:
Say I have an interface with one method, let's call it Execute(EnumedParam action). I'd like to be able to call it from the client with

InterfaceType.Execute(Action.One);

and on the server to create an instance based on action and execute it's Execute method.

Also there might be many instances of the class and I'd like the client not to know anything about the classes, just the interface.

How can I do that over WCF?

(note: If my class model is totally wrong can you recommend a book or a blog where I can read more about this?)

I can't paste code in comments for another edit

Wouter de Kort gave great example of what am I doing. But how do I setup endpoints for that? Looking at the example given here http://www.switchonthecode.com/tutorials/wcf-tutorial-basic-interprocess-communication - the author opens the port like this:

using (ServiceHost host = new ServiceHost(
  typeof(StringReverser),
  new Uri[]{
    new Uri("http://localhost:8000"),
    new Uri("net.pipe://localhost")
  }))
{

Now that's where my problem is. The first parameter is a class (can't be an interface or abstract class). Do I have to do it for every class that extends the interface or can I somehow use the same host for multiple classes?

Upvotes: 0

Views: 239

Answers (1)

Wouter de Kort
Wouter de Kort

Reputation: 39898

Let's say you have the following service interface:

public interface IMyService 
{
    void Execute(EnumdParam action);
}

If you want to use this in WCF you will decorate it:

[ServiceContract]
public interface IMyService 
{
   [OperationContract]
   void Execute(EnumdParam action);
}

On your client you have to create a Proxy to access the WCF Service.

[System.Diagnostics.DebuggerStepThroughAttribute()]
public partial class MyServiceClient : ClientBase<IMyService>, IMyService
{
    public MyServiceClient ()
    {
    }

    public void Execute(EnumdParam action);
    {
        return base.Channel.Execute(action);
    }
}

As you can see, your client proxy implements IMyService so in your client code you only have to be aware of the IMyService interface. If you change your factory to return MyServiceClient instead of MyService nothing in your client code has to change (except for WCF configuration and making sure you dispose of the client).

Upvotes: 2

Related Questions