GigaPr
GigaPr

Reputation: 5386

Create WCF Client without auto generated proxy

looking at

WCF ChannelFactory vs generating proxy

appears that the best practice in creating a WCF client is to create a proxy (Not autogenerated).

I've been looking online for a while and i didn't find any complete example(Proxy class, web.config)

Could you provide an example or links to resources?

Upvotes: 22

Views: 34237

Answers (3)

Igby Largeman
Igby Largeman

Reputation: 16747

This is how I do it.

Get service contracts and data contracts

If I have access to the service code, I have all the contracts. If not, I can use svcutil or Add Service Reference to generate them.

Make config

I use Add Service Reference just to get the app.config file. I then delete everything else it generates. Edit the app.config as necessary.

Define factory

Say I have a service contract IFooService:

interface IFooServiceChannel : IFooService, IClientChannel { }

That is literally it. No members.

Create factory

fooServiceFactory = new ChannelFactory<IFooServiceChannel>(
                        "NetTcpBinding_IFooService");

The string "NetTcpBinding_IFooService" is the name attribute of the binding element in app.config.

Create channel

fooService = fooServiceFactory.CreateChannel();

Use it

fooService.DoSomething();

The trickiest part is getting app.config right. You need to learn about bindings and endpoints. It's a bit of a learning curve, but nothing drastic.

Upvotes: 11

cadrell0
cadrell0

Reputation: 17337

Here are the basic steps.

  1. Create your service like normal.
  2. Move the interface that your service implements into an assembly that can be shared with the client.
  3. Create a ChannelFactory where T is your interface. You will have to give the uri of your service to the constructor.
  4. Call factory.CreateChannel(). This will be type T.
  5. Use the channel to make calls.

It is really that simple. No auto generated code, no service references. It gets a little more complicated with async calls and Silverlight, but not too much.

Upvotes: 9

Tad Donaghe
Tad Donaghe

Reputation: 6588

This article is about exactly what you're asking, I believe:

WCF the Manual Way... The Right Way

Having shared that, though, creating your proxies manually is probably not always the best possible use of your time. The article goes into some great reasons for doing so - you'll certainly have more control, your clients may have an easier time, etc. but overall, doing things manually like this will require more of your time, and explaining to users of your service exactly how to use the proxy you provide may be a pain.

There's a reason WCF allows metadata exchange and discovery and VS will auto create proxies for you.

Either way, it's a cool article and a technique well worth learning.

Upvotes: 20

Related Questions