【问题标题】:WCF Service - runtime not seeing the ServiceContract on InterfaceWCF 服务 - 运行时看不到接口上的 ServiceContract
【发布时间】:2010-10-10 04:58:08
【问题描述】:

我是 WCF 新手,正在尝试运行我的第一个服务。我很接近但被困在这个问题上。

在我的接口定义文件中,我有这个:

[ServiceContract(Namespace="http://mysite.com/wcfservices/2009/02")]       
    public interface IInventoryService
    {
        [OperationContract]
        string GetInventoryName(int InventoryID);
    }

然后我有我的类文件(用于服务)继承它:

   public class InventoryService : IInventoryService
    {
        // This method is exposed to the wcf service
        public string GetInventoryName(int InventoryID)
        {
            return "White Paper";
        }

最后,在我的 Host 项目中,我有这个:

    ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
    host.AddServiceEndpoint(typeof(Inventory.InventoryService), new NetTcpBinding(),
        "net.tcp://localhost:9000/GetInventory");
    host.Open();

一切都编译得很好,当主机去添加服务端点时,它会爆炸:“合同类型 Inventory.InventoryService 没有使用 ServiceContractAttribute 属性。为了定义一个有效的合同,指定的类型(合同接口或服务类)必须使用 ServiceContractAttribute 进行属性化。”

我知道我在这里遗漏了一些简单的东西。我将接口明确标记为服务合同,并且在 Host 项目中有对该项目的引用。

【问题讨论】:

    标签: wcf binding interface service servicehost


    【解决方案1】:
    ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
    host.AddServiceEndpoint(typeof(Inventory.InventoryService), new NetTcpBinding(),
        "net.tcp://localhost:9000/GetInventory");
    host.Open();
    

    如果您的 ServiceContract 属性位于 Interface 而不是具体类上,请尝试以下操作:

    ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
    host.AddServiceEndpoint(typeof(Inventory.IInventoryService), new NetTcpBinding(),
        "net.tcp://localhost:9000/GetInventory");
    host.Open();
    

    【讨论】:

    • 当我尝试它给我 ArgumentException 时,“ServiceHost 仅支持类服务类型。”
    • 换错了——将 AddServiceEndpoint 调用改为接口,保持 ServiceHost 为类。
    • 知道了!所以我正在实例化 ServiceHost,传入具体的类,但我正在使用接口定义端点或绑定,这实际上是合同定义(即不是类)。我最终会得到这个窍门。谢谢布赖恩和安德鲁。
    猜你喜欢
    • 2012-07-23
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多