我正在通过快速入门研究 Prism v2。我创建了一个具有以下签名的 WCF 服务:
namespace HelloWorld.Silverlight.Web
{
[ServiceContract(Namespace = "http://helloworld.org/messaging")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloWorldMessageService
{
private string message = "Hello from WCF";
[OperationContract]
public void UpdateMessage(string message)
{
this.message = message;
}
[OperationContract]
public string GetMessage()
{
return message;
}
}
}
当我在 silverlight 项目中添加对此服务的服务引用时,它会生成一个接口(interface)和一个类:
[System.ServiceModel.ServiceContractAttribute
(Namespace="http://helloworld.org/messaging",
ConfigurationName="Web.Services.HelloWorldMessageService")]
public interface HelloWorldMessageService {
[System.ServiceModel.OperationContractAttribute
(AsyncPattern=true,
Action="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessage",
ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessageResponse")]
System.IAsyncResult BeginUpdateMessage(string message, System.AsyncCallback callback, object asyncState);
void EndUpdateMessage(System.IAsyncResult result);
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://helloworld.org/messaging/HelloWorldMessageService/GetMessage", ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/GetMessageResponse")]
System.IAsyncResult BeginGetMessage(System.AsyncCallback callback, object asyncState);
string EndGetMessage(System.IAsyncResult result);
}
public partial class HelloWorldMessageServiceClient : System.ServiceModel.ClientBase<HelloWorld.Core.Web.Services.HelloWorldMessageService>, HelloWorld.Core.Web.Services.HelloWorldMessageService {
{
// implementation
}
我试图通过传递接口(interface)而不是具体类来解耦我的应用程序。但我很难找到如何做到这一点的例子。当我尝试调用 EndGetMessage 然后更新我的 UI 时,我得到一个关于在错误线程上更新 UI 的异常。如何从后台线程更新 UI?
我试过了,但我得到了
UnauthorizedAccessException : Invalid cross-thread access
.string messageresult = _service.EndGetMessage(result);
Application.Current.RootVisual.Dispatcher.BeginInvoke(() => this.Message = messageresult );
Application.Current.RootVisual
抛出异常.
最佳答案
这是我喜欢做的事情......服务代理是用一个接口(interface)生成的
HelloWorldClient : IHelloWorld
但问题是
IHelloWorld
不包括该方法的异步版本。所以,我创建了一个异步接口(interface):public interface IHelloWorldAsync : IHelloWorld
{
void HelloWorldAsync(...);
event System.EventHandler<HelloWorldEventRgs> HelloWorldCompleted;
}
然后,您可以告诉服务代理通过部分实现接口(interface):
public partial class HelloWorldClient : IHelloWorldAsync {}
因为
HelloWorldClient
确实,实现了那些异步方法,这是可行的。然后,我可以使用
IHelloWorldAsync
到处告诉UnityContainer
使用 HelloWorldClient
对于 IHelloWorldAsync
接口(interface)。
关于wcf - 将 Silverlight 客户端与服务引用生成的类解耦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/617377/