协定类型不具有 ServiceContractAttribute 特性

WCF自定义的一个服务,开启时,提示:协定类型不具有 ServiceContractAttribute 特性

代码执行后报如下错误:



解决方法如下:


 将契约接口public static readonly Type ContractType = typeof(HelloService.HelloService);中的 typeof(HelloService.IHelloService)


下附源代码:

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


namespace HelloServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MyHelloHost host=new MyHelloHost())
            {
                host.Open();
                Console.ReadKey();
            }
        }
    }



    public class MyHelloHost : IDisposable
    {
        /// <summary>
        /// 定义一个服务对象
        /// </summary>
        private ServiceHost _myhost;
        public ServiceHost Myhost
        {
            get { return _myhost; }
        }


        /// <summary>
        /// 定义一个基地址
        /// </summary>
        public const string BaseAddress = "net.pipe://localhost";


        /// <summary>
        /// 可选地址
        /// </summary>
        public const string HelloServiceAddress = "Hello";


        /// <summary>
        /// 服务契约实现类型
        /// </summary>
        public static readonly Type ServiceType=typeof(HelloService.HelloService);


        /// <summary>
        /// 服务契约接口
        /// </summary>
        public static readonly Type ContractType = typeof(HelloService.HelloService);


        /// <summary>
        /// 定义一个绑定
        /// Binding来自“using System.ServiceModel.Channels;”命名空间
        /// NetNamedPipeBinding:提供了一个既安全又可靠且针对计算机上的通信进行了优化的绑定
        /// </summary>
        public static readonly Binding hellobinding = new NetNamedPipeBinding();

        /// <summary>
        /// 构造服务对象
        /// </summary>
        protected void CreateHelloServiceHost()
        {
            //创建服务对象
            _myhost = new ServiceHost(ServiceType, new Uri [] { new Uri(BaseAddress) });
            //添加终结点
            _myhost.AddServiceEndpoint(ContractType,hellobinding,HelloServiceAddress);
        }

        /// <summary>
        /// 打开服务的方法
        /// </summary>
        public void Open()
        {
            Console.WriteLine("开始启动服务......");
            _myhost.Open();
            Console.WriteLine("服务已经启动......");
 
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        public MyHelloHost()
        {
            CreateHelloServiceHost(); 
        }

        /// <summary>
        /// 销毁服务宿主对象实例
        /// </summary>
        public void Dispose()
        {
            if (_myhost!=null)
            {
                (_myhost as IDisposable).Dispose();
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值