通過反射該變WCF的Endpoint的行為,而無需修改用戶端設定檔

來源:互聯網
上載者:User

1,首先,修正了一個由於List<TEntity>資料量過大導致的異常:

http://www.cnblogs.com/sinxsoft/archive/2010/11/10/1874249.html

2,修正了此問題之後,發現修改了用戶端的app.config檔案,這對於發布及其不爽,因為每個客戶的app.config不同,這會導致發布後每個客戶機上的檔案一致;

於是,想用代碼動態設定終結點的行為。

3,在調試過程中,先配置好了用戶端,發現了ChannelFactory<T> 的終結點行為列表已經包括了對象: System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior,通過reflector一查,發現該對象的定義為internal:

internal class DataContractSerializerServiceBehavior : IServiceBehavior, IEndpointBehavior

4,於是機會有了:可以通過反射建立對象塞入到終結點的行為列表中了:

      private static ChannelFactory<IServiceChannel> GetChannelFactory()
        {
            if (_factory == null)
            {
                _factory = new ChannelFactory<IServiceChannel>("BasicHttpBinding_IService");
                AttachServiceBehavior(_factory);
            }
            return _factory;
        }

        private static void AttachServiceBehavior(ChannelFactory<IServiceChannel> channelFactory)
        {
            //找到程式集的其中任何一個class,確定程式集
            var type = typeof (ClientRuntime);
            //執行個體化internal類,通過反射
            var instance =
                type.Assembly.CreateInstance("System.ServiceModel.Dispatcher.DataContractSerializerServiceBehavior",
                                             true,
                                             BindingFlags.CreateInstance | BindingFlags.Instance |
                                             BindingFlags.NonPublic, null, new object[] {false, Int32.MaxValue}, null,
                                             null);
            //轉換成終結點的行為介面
            var behavior = instance as IEndpointBehavior;
            if (behavior != null)
            {
                //插入到通道處理站的終結點行為集合中
                channelFactory.Endpoint.Behaviors.Add(behavior);
            }
        }

 

 測試,通過

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.