Override ToString Method in WCF Service

This is the class generated by the service:

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

I use my service. In MyClass I overridden ToString() , but I do not have it in my client. I want to either generate it, or how MyClass is partial, can I override ToString myself?

I know that I can write in the generated .cs file. What is the best way to do this, and generally should I do this?

+6
source share
2 answers

If you define both the client and the service, you do not need to use the WSDL generation classes. Move the shared objects to a separate assembly and refer to it from both client and server projects. When you create a link to a service, there is an β€œadvanced” option (in my opinion, enabled by default) that reuses any known classes from WSDL instead of generating new ones.

Even better, if you move the service contract to your shared library, you don’t even need to create a link to the service, you can just call ChannelFactory directly and exclude the entire automatically generated proxy class.

I have a demo of 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 WSDL from the service (for example, you do not have control over the service and it can change for you), you can extend the partial classes created by VS (as you suggested). Most of the auto-generated classes that you get from VS these days are partial classes, specifically to make such an extension possible. The disadvantage, of course, is that nothing guarantees that the client and additional methods of the partial class will be the same. I would definitely think that this is a variant of the last resort.

+6
source

If you are sharing a dll where the overriden method is used between the client and server project, you can use this method. By default, WCF generates each class only with properties declared in the service interface. The method is not generated.

You can simply create a separate dll file and put what you want to share between the service and the client in this dll; and add this DLL as a reference to customer and service projects. By default, when generating a proxy, it will not automatically generate common classes.

+3
source

Source: https://habr.com/ru/post/917182/


All Articles