为什么将WCF代理从Silverlight移动到可移植类库需要实现CreateChannel

本文关键字:类库 可移植 CreateChannel 实现 移动 WCF 代理 Silverlight 为什么 | 更新日期: 2023-09-27 18:28:19

我有一个WCF服务,它是从Silverlight UI调用的。代理在Silverlight代码中定义,如下所示:

public class MyServiceProxy : ClientBase<IMyService>, IMyService
{
    public IAsyncResult BeginGetId(string name, AsyncCallback callback, object asyncState)
    {
        return this.Channel.BeginGetId(name, callback, asyncState);
    }
    public int EndGetId(IAsyncResult result)
    {
        return this.Channel.EndGetId(result);
    }
}

我现在想从Silverlight中没有的另一个应用程序调用WCF。我想我应该尝试通过将代理移动到一个针对.Net 4和Silverlight 5的可移植类库中来共享它。

在移动类之后,接口现在希望我覆盖CreateChannel:

protected override IMyService CreateChannel()

我不知道我应该在这里提供什么实现。在PCL中共享代理是明智之举,还是我的做法不对?

为什么将WCF代理从Silverlight移动到可移植类库需要实现CreateChannel

我知道这个问题现在很老了,但我最近遇到了这个问题,花了一段时间才找到答案,所以希望这能帮助人们节省一些时间。

如果您在PCL中以Silverlight为目标,则ChannelFactory<T>不可用,因此您必须在ClientBase<T>上创建自己的CreateChannel()实现。

如果您想避免自己实现CreateChannel(),那么您只能针对.NET 4.5和Windows 8和/或Windows Phone Silverlight 8。

如果选择Windows Phone Silverlight 7或7.5,它将自动要求Silverlight 4或更高版本。同样,如果您选择Windows Phone Silverlight 8,但.NET版本低于4.5,则它将自动需要Silverlight 5。两者都将迫使您提供自己的CreateChannel()实现。

以Windows Phone 8.1为目标将完全删除ClientBase<T>,因为System.ServiceModel在Windows Phone 8.1中不可用。