Programmatically setting MaxItemsInObjectGraph in WCF
Wednesday, September 30, 2009 at 11:00PM Recently I ported an Asp.Net web service based application to use WCF. Everything was working great until I tried to return an array with 10,416 items in it. Normally this is an easy fix. Simply create a DataContractSerializer behavior with a larger MaxItemsInObjectGraph setting in your config file.
4 <behaviors>
5 <endpointBehaviors>
6 <behavior name="MaxObjects">
7 <dataContractSerializer maxItemsInObjectGraph="3000000" />
8 </behavior>
9 </endpointBehaviors>
10 </behaviors>
29 <endpoint address="net.tcp://localhost:4200"
behaviorConfiguration="MaxObjects" />
This needs to be done on both the client and the server. Unfortunately, this method won’t work for my client app. The client creates all the endpoints programmatically.
The process of setting this in code isn’t quite as straightforward as I’d expected. It turns out the DataContractSerializer behaviors have to be applied to the constructor of the serializer. Normally when you create a ServiceEndPoint in code you aren’t creating the DataContractSerializer, the ServiceEndPoint constructor is. I’ve seen examples online of people creating custom serializers but that’s overkill for just changing this setting.
I found it much easier to change the setting on the Operation behaviors after the EndPoint has been created. The only tricky thing is you need to change it for every Operation that needs a larger MaxItem count. For simplicity, I created a function to chang it for all operations on the endpoint.
166 ServiceEndpoint endpoint = new ServiceEndpoint(
168 UpdateMaxItemsBehavior(endpoint, 300000000);
…
protected void UpdateMaxItemsBehavior(ServiceEndpoint endpoint, int maxItems)
{
foreach (OperationDescription operation in endpoint.Contract.Operations)
{
operation.Behaviors.Find<
DataContractSerializerOperationBehavior
>().MaxItemsInObjectGraph = maxItems;
}
}
.NET,
WCF in
Programming
Reader Comments