代码改变世界

WCF 学习记录(2)

2012-02-03 20:42  java线程例子  阅读(179)  评论(0编辑  收藏  举报
 


1、突破WCF一些限制的方法:

   A)通过配置来完成
         可在web.config或者app.config中配置,这种方法可参见前面的文章;

   B) 可通过代码实现
        前面的方法有个缺陷,就是自己写宿主服务的时候实现比较难,而且我感觉不适很方便,我喜欢在代码中控制:

      

public static ChannelFactory<ISvc> CreateChannelFactory<ISvc>(string RemoteAddress, string ServiceName)
        {
            BasicHttpBinding theBinding = new BasicHttpBinding();
            theBinding.MaxReceivedMessageSize = int.MaxValue;//接受消息最大size.
            theBinding.MaxBufferSize = int.MaxValue;//缓冲区大小,这个值可以不设定这么大.
            theBinding.MaxBufferPoolSize = int.MaxValue;//缓存池大小
            theBinding.ReaderQuotas.MaxDepth=32;//序列化时的深度,对象成员会嵌套,而且容易循环嵌套,这里设置序列化时
            //的解析深度.(序列化是递归进行的)
            theBinding.ReaderQuotas.MaxStringContentLength= 2147483647;//最大字符串长度
            theBinding.ReaderQuotas.MaxArrayLength= 2147483647;//对象数量
            theBinding.ReaderQuotas.MaxBytesPerRead = 2147483647;//每次读字节数,可不设这么大.
            theBinding.ReaderQuotas.MaxNameTableCharCount = 2147483647;

            ServiceEndpoint httpEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(ISvc)),
                theBinding,
                new EndpointAddress(theRemoteAddress + ServiceName));
            //这里也可以优化只怎对当前的调用,而不需要针对所有的调用.这相当于在配置文件中加:                                   //<behavior name="WCFCommonConfig">            
            //<dataContractSerializer maxItemsInObjectGraph="2147483647" />            
            //</behavior>
            foreach (var op in httpEndpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }
            return new ChannelFactory<ISvc>(httpEndpoint);
        }

上面两种方式情况下,如果还会报错,就要注意在服务器端配置文件中 <system.web>节增加<httpRuntime maxRequestLength="2147483647" executionTimeout="600"/>

在<serviceBehaviors>节中的<behavior>里增加<serviceThrottling
               maxConcurrentCalls="1000"
              maxConcurrentSessions="1000"
              maxConcurrentInstances="1000"/>

这个可以解决同时请求过多而出现的错误。<behavior>如果不命名,应该是适合所有服务(不确定,没进行过对比试验,谁知道,可以告知一下)

 

整体上来讲,我喜欢自己写宿主这种方式,客户端也采用手工代码邦定的方式,采用添加服务引用的方式,一旦服务端发生变化,客户端需要刷新,而且会生成很多文件,感觉不适很好,而客户端采用代码动态 绑定则只要更新服务接口就可以,要简单很多。