Search code examples
wcfbindinginterfaceserviceservicehost

WCF Service - runtime not seeing the ServiceContract on Interface


I'm new to WCF and trying to get my first service running. I'm close but stuck on this problem.

In my interface definition file, I have this:

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

Then I have my class file (for the service) that inherits it:

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

Finally, in my Host project I have this:

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

Everything compiles fine, and when the host goes to add the service endpoint, it bombs with this: "The contract type Inventory.InventoryService is not attributed with ServiceContractAttribute. In order to define a valid contract, the specified type (either contract interface or service class) must be attributed with ServiceContractAttribute."

I know I'm missing something simple here. I have the interface clearly marked as a service contract and there's a reference to that project in the Host project.


Solution

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

    If your ServiceContract attribute is on the Interface not the concrete class, try the following:

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