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();
}
}
}
}