在 Silverlight 中,如果用 VS 添加对 WCF Service,的引用,则会自动生成 ServiceReferences.ClIEntConfig 配置文件,其中包含该 Service 的 Binding 和 Address 等信息。将配置信息隔离出来本来是好事情,但问题是,由于 Silverlight 只是一个客户端 runtime 的特性决定,配置文件将被在编译时组装到 Siverlight 的 xap 压缩包中去,这样,修改配置就会变得很麻烦,每次要修改后重新编译,重新部署。而由 VS 生成的这个 config 文件中往往包含了对 Service 所在地址的直接引用。比如 http://localhost:123/SomeService.svc,这样,对我们部署到生产环境是非常不方便的。
换一个做法,如果我们能将承载 Silverlight 的页面跟 WCF Service 放到同一个网站中,这样就可以用相对地址来访问到 Service. 在开发环境/测试环境/生产环境之间迁移就会变得很方便。
这时该网站下的文件结构大致如下:
根
|_ Service1.svc
|_ Service2.svc
|_ ...
|_ ClIEntBin
|_ YourSilverlightApp.xap
其中 ClIEntBin 下是编译生成的 Silverlight 程序的 xap 包。
根据这个结构,我们就可以做一个 WcfServiceClIEntFactory 类,可以按需创建出指定类型的 WCF 客户端代理类,而不用去读取配置文件。代码如下:
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 });
}
}
}
这样,就可以利用类似下面的代码来创建客户端代理:
MemberService>.CreateServiceClIEnt();
比起直接用 new 的方式创建,多传了两个类型参数而已,但是却不需要依赖于配置文件了。
至于上面提到的 WCF Service 跟 Silverlight 的程序集放置的这个特定结构,其实也不一定要这样的。用上面提供的第二个重载形式 public static TServiceClIEnt CreateServiceClIEnt(string serviceAddress) 就可以指定其他情况的相对地址。当然,如果一定要用绝对地址,增加一个类似的方法就可以了,这里我省略了。 不过,我个人而言比较喜欢这种结构,合理的约定就会省去很多编程和配置的麻烦。 Ruby on Rails 的哲学不是有一个叫做“约定胜于配置”么。
以上是内存溢出为你收集整理的[Silverlight]摆脱对 ServiceReferences.ClientConfig 的依赖全部内容,希望文章能够帮你解决[Silverlight]摆脱对 ServiceReferences.ClientConfig 的依赖所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)