换一个做法,如果我们能将承载 Silverlight 的页面跟 WCF Service 放到同一个网站中,这样就可以用相对地址来访问到 Service. 在开发环境/测试环境/生产环境之间迁移就会变得很方便。
这时该网站下的文件结构大致如下:
根
|_ Service1.svc
|_ Service2.svc
|_ ...
|_ ClientBin
|_ YourSilverlightApp.xap
其中 ClientBin 下是编译生成的 Silverlight 程序的 xap 包。
根据这个结构,我们就可以做一个 WcfServiceClientFactory 类,可以按需创建出指定类型的 WCF 客户端代理类,而不用去读取配置文件。代码如下:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace NeilChen.Silverlight
{
public static class WcfServiceClientFactory<TServiceClient, TService>
where TServiceClient : ClientBase<TService>, TService
where TService : class
{
public static TServiceClient CreateServiceClient()
{
var typeName = typeof(TService).Name;
var serviceAddress = "../" + typeName + ".svc";
return CreateServiceClient(serviceAddress);
}
public static TServiceClient CreateServiceClient(string serviceAddress)
{
var endpointAddr = new EndpointAddress(new Uri(Application.Current.Host.Source, serviceAddress));
var binding = new BasicHttpBinding();
var ctor = typeof(TServiceClient).GetConstructor(new Type[] { typeof(Binding), typeof(EndpointAddress) });
return (TServiceClient)ctor.Invoke(new object[] { binding, endpointAddr });
}
}
}
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace NeilChen.Silverlight
{
public static class WcfServiceClientFactory<TServiceClient, TService>
where TServiceClient : ClientBase<TService>, TService
where TService : class
{
public static TServiceClient CreateServiceClient()
{
var typeName = typeof(TService).Name;
var serviceAddress = "../" + typeName + ".svc";
return CreateServiceClient(serviceAddress);
}
public static TServiceClient CreateServiceClient(string serviceAddress)
{
var endpointAddr = new EndpointAddress(new Uri(Application.Current.Host.Source, serviceAddress));
var binding = new BasicHttpBinding();
var ctor = typeof(TServiceClient).GetConstructor(new Type[] { typeof(Binding), typeof(EndpointAddress) });
return (TServiceClient)ctor.Invoke(new object[] { binding, endpointAddr });
}
}
}
这样,就可以利用类似下面的代码来创建客户端代理:
var memberService = WcfServiceClientFactory<MemberServiceClient,
MemberService>.CreateServiceClient();
MemberService>.CreateServiceClient();
比起直接用 new 的方式创建,多传了两个类型参数而已,但是却不需要依赖于配置文件了。
至于上面提到的 WCF Service 跟 Silverlight 的程序集放置的这个特定结构,其实也不一定要这样的。用上面提供的第二个重载形式 public static TServiceClient CreateServiceClient(string serviceAddress) 就可以指定其他情况的相对地址。当然,如果一定要用绝对地址,增加一个类似的方法就可以了,这里我省略了。
不过,我个人而言比较喜欢这种结构,合理的约定就会省去很多编程和配置的麻烦。
Ruby on Rails 的哲学不是有一个叫做“约定胜于配置”么。