Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override ToString method in WCF service

This is my service generated class:

public partial class MyClass : object, 
                               System.Runtime.Serialization.IExtensibleDataObject, 
                               System.ComponentModel.INotifyPropertyChanged 
{ }

I'm using my own service. In MyClass I have overridden ToString() but I don't have it in my client. I want either to generate it or as MyClass is partial am I able to override ToString myself?

I know that I can write in generated .cs file. What is the best way to do it and at all should I do it?

like image 428
levi Avatar asked Jun 01 '12 12:06

levi


1 Answers

If you are defining both the client and the service, you don't need to use the WSDL-generate classes. Move the shared objects into a separate assembly, and reference it from both client and server projects. When you create the service reference, there's an "advanced" option (which I think is on by default) that reuses any known classes from the WSDL instead of generating new ones.

Even better, if you move the service contract into your shared library, you don't even need to create the service reference, you can just call the ChannelFactory directly and eliminate the entire auto-generated proxy class.

I have a demonstration on how to do both of these things on my blog: http://blog.kutulu.org/2012/03/proxy-free-wcf-ditching-proxy.html

If you absolutely need to use the WSDL from the service (e.g. you don't have control over the service side and it could change on you), then you can extend the partial classes that VS creates (as you suggested). Most auto-generate classes you get from VS these days are partial classes specifically to make this kind of extension possible. The downside, of course, is that nothing guarantees client and server's additional partial class methods are the same. I'd definitely consider this a last-resort option.

like image 56
Michael Edenfield Avatar answered Sep 23 '22 22:09

Michael Edenfield