30.03.2009 г.

Consuming WCF Service in a library

To be able to consume a WCF service you have to create a service proxy client that is used to call service operations. It is not something different than consuming an ASP.NET web service.
You can get a proxy client using 4 different approaches:
1) Generate it using Visual Studio
2) Generate it using the command line tool svcutil.exe
3) Manually defining a proxy class
4) Using ChannelFactory class

However only 1) and 2) are good for me because in 3) and 4) you need to know the type of the service contract prior to creation.
In 1) and 2) the service metadata is used instead for generating the service contract, datacontract and so on on the client side. Btw 1) and 2) are practically equivalent because Visual Studio is using svcutil.exe to create the service reference. Svcutil just gives us some other options.

So let me step in a problem I ran into today.
Because I like the approach with configuring a service client in a configuration file rather than doing this in code, I was surprised to find today that there is no straightforward way of consuming a WCF service from a project that compiles in a dll.
That is very strange. The reason is that when creating an instance of the proxy client class without passing a Binding and EndpointAddress in the constructor (using the parameterless ctor) these are read from the app.config file. And in a library project this is impossible for the WCF framework.
You will get error like :
"Could not find default endpoint element that references contract ...


I should say that I didn't have any problems creating a service reference in the library project and also service client configuration was added to my app.config file. But what for if this configuration can not be read.
Some will probably say why not creating a Binding and EndpointAddress objects in code and then pass them to the ctor for the proxy client. Answer is that I don't want to change my code every time I change something in my service configuration. I just want to update the reference and have all the necessary configuration generated for me in the configuration file.
This problem is important when you design VSTO MS Office Add-ins, because these add-ins compile to a dll, not executable. So I'm curious how can I consume WCF services in a VSTO Add-in with still configuring my service client in a configuration file.

I read lots of forum threads today trying to find the solution and found out that there are other developers experiencing the same problem. The only solution I consider good is to create a parser for a custom configuration file and to load the library configuration and extract it.

HERE is a example of this approach, but the posted class needs to be extended to parse at least binding customizations in the configuration file that it opens.

However I think Microsoft should have thought about this more when designing WCF.

Няма коментари:

Публикуване на коментар