我有一个带有回调接口的简单 WCF 应用程序。我想要的是在客户端的回调函数中调用其他 WCF 服务。
但是当我尝试做时,我得到了例外
DetailsSystem.ServiceModel.CommunicationException:服务器没有提供有意义的回复;这可能是由合同不匹配、会话过早关闭或内部服务器错误引起的。
以下是合同:
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
public interface IMyService
{
[OperationContract]
void DoAddition(int numberOne, int numberTwo);
[OperationContract]
double Pow(double number, double power);
}
public interface IMyServiceCallback
{
[OperationContract]
void OnCallback(string result);
}
这是简单的服务实现
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyCustomService : IMyService
{
public void DoAddition(int numberOne, int numberTwo)
{
Console.WriteLine("Now Do Addition called");
var callback = OperationContext.Current.
GetCallbackChannel<IMyServiceCallback>();
callback.OnCallback("The result is=" + numberOne + numberTwo );
}
public double Pow(double number, double power)
{
double result = 0;
try
{
Console.WriteLine("Now Pow called");
result= Math.Pow(number, power);
}
catch (Exception e)
{
Console.WriteLine("Error:" + e);
}
return result;
}
}
我将此作为服务托管在控制台中
callServiceHost = new ServiceHost(typeof(MyService.MyCustomService));
callServiceHost.AddServiceEndpoint(typeof (IMyService), new WSDualHttpBinding(), new Uri(GetUri()));
callServiceHost.Open();
Console.WriteLine("Press to terminate.\n\n");
Console.ReadLine();
在客户端,我想在回调函数中调用 wcf 服务,这样
[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
public class MyServiceCallback : IMyServiceCallback
{
public void OnCallback(string result)
{
Console.WriteLine("From Server I got the result" + result);
Console.WriteLine(result);
double powValue = Service.Pow(2, 3);
Console.WriteLine("Power=" + powValue);
}
public IMyService Service { get; set; }
}
我的客户代码是
var binding = new WSDualHttpBinding();
var address = new EndpointAddress(GetUri());
var callback = new MyServiceCallback();
var instanceContext = new InstanceContext(callback);
var factory = new DuplexChannelFactory<IMyService>(instanceContext, binding, address);
IMyService callService = factory.CreateChannel();
callback.Service = callService;
callService.DoAddition(4,6);
Console.ReadKey();