解决WCF双工通讯模式中向ChannelFactory提供的InstanceContext包含未实现CallbackContractType的问题

最近在苦学WCF,把我遇到的WCF双工通讯模式的一个小问题呈现出来,同时在网上找了一下发现也有很多网友,也有此问题“向ChannelFactory提供的InstanceContext包含未实现CallbackContractType”!

好了废话不多说,贴出代码解决问题!

1.项目结构(myWcfService是个wcf服务库项目,wcfClient是个简单的winform项目)

2.IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace myWcfService
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IServiceDuplexCallback))]
    public interface IService1
    {
        [OperationContract(IsOneWay=true)]
        void AddNumber(int x,int y);
        [OperationContract(IsOneWay=true)]
        void Subtract(int x,int y);
    }
    public interface IServiceDuplexCallback
    {
        [OperationContract(IsOneWay=true)]
        void Calculate(int result);
    }
}

3.Service1.cs服务实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace myWcfService
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    public class Service1 : IService1
    {
        IServiceDuplexCallback callback
        {
            get { return OperationContext.Current.GetCallbackChannel<IServiceDuplexCallback>(); }
        }
        public void AddNumber(int x, int y)
        {
            int z = x + y;
            callback.Calculate(z);
        }

        public void Subtract(int x, int y)
        {
            int z = x - y;
            callback.Calculate(z);
        }
    }
}

4.callbackhandler.cs服务回调的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace wcfClient
{
    public class CallbackHandler : ServiceReference1.IService1Callback
    {

        public void Calculate(int result)
        {
            System.Windows.Forms.MessageBox.Show("计算结果是:"+result);
        }
    }
}

5.

事件的实现代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;


namespace wcfClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            InstanceContext ic = new InstanceContext(new CallbackHandler());
            ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(ic);
            client.AddNumber(3,4);
        }
    }
}

最终的问题就出在第四步:

这里的实现应该是添加服务引用的时候,应该是自动生成的在客户端的代理类,否则会报如题所示的错误!

原文地址:https://www.cnblogs.com/zpc870921/p/2658669.html