代码改变世界

WCF 附录 高级主题 从元数据创建客户端

2011-06-12 10:29  DanielWise  阅读(608)  评论(0编辑  收藏  举报
MetadataResolver类允许使用程式而不是使用配置文件来收集绑定信息。这意味着客户端可以动态创建而不需要确定一个配置文件。如果你想部署客户端然后再改服务的配置的话那么这个很有用。列表A.1 显示了如何使用MetadataResolver类来指向一个已知的元数据终结点的例子。MetadataResolver类的Resolve方法用来创建绑定信息。绑定信息包含了一个或多个ServiceEndpoint实例。每个可用的终结点都有一个ServiceEndpoint实例。ServiceEndpoint实例用来创建一个客户端。
列表A.1 使用MetadataResolver类
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void GetPriceButton_Click(object sender, EventArgs e)
        {
            Type typeOf = typeof(ISimpleStockService);
            Uri metadataUri = new Uri("http://localhost:58609/SimpleStockService.svc/mex");
            EndpointAddress metadataAddress = new EndpointAddress(metadataUri);
            ServiceEndpointCollection endpoints = MetadataResolver.Resolve(typeOf, metadataAddress);
            string symbol = SymbolTextBox.Text;
            decimal price;

            foreach (ServiceEndpoint point in endpoints)
            {
                if (point != null)
                {
                    using (ChannelFactory<ISimpleStockService> cf = 
                        new ChannelFactory<ISimpleStockService>(point))
                    {
                        ISimpleStockService client = cf.CreateChannel();
                        price = client.GetQuote(symbol);
                        SymbolPricesListBox.Items.Insert(0, symbol + "=" + price.ToString());
                    }
                }
            }
        }
    }