This can be done using the following two steps:
First we implement the IDatacontractSurrogate interface:
class MySurrogate : IDataContractSurrogate { public Type GetDataContractType(Type type) {
Secondly, set the surrogate to ServiceHost as follows:
foreach (var endpoint in serviceHost.Description.Endpoints) { foreach (var operation in endpoint.Contract.Operations) { operation.Behaviors.Find<DataContractSerializerOperationBehavior>().DataContractSurrogate = new MySurrogate(); } }
Remember to do this before opening the host server. Otherwise, this may not work.
If you use IIS hosting and specify WebServiceHostFactory in the .svc file, then, of course, you have no way to install a surrogate. To overcome this, you have two options:
Create a custom service behavior attribute and set a surrogate in its ApplyDispatchBehavior() method. After you place this attribute on your device, WCF will automatically execute this method and the surrogate will be installed.
Create your own custom service host by subclassing WebServiceHost . Then set the surrogate to the ApplyConfiguration() method. This will also have the same effect.
source share