3

我是 WCF 和 C# 的新手。

我正在尝试使用 1 个方法(Do)创建一个具有 1 个接口(IA)的 WCF 服务,该方法具有 2 个实现(A1 和 A2)。

一个愚蠢的例子:

IA.cs:

namespace IA_NS
{
    [ServiceContract]
    public interface IA
    {
        [OperationContract]
        int Do(B b);
    }

    [DataContract]
    public class B
    {
        [DataMember]
        public string b1 { get; set; }
    }
}

A1.cs:

namespace A1_NS
{
    public class A1 : IA
    {
        public int Do(B b) {...}
    }
}

A2.cs:

namespace A2_NS
{
    public class A2 : IA
    {
        public int Do(B b) {...}
    }
}

我的自助托管控制台,我在其中托管两种服务:

class Program
{
    static void Main(string[] args)
    {
        ServiceHost hostA1 = new ServiceHost(typeof(A1_NS.A1));
        hostA1.Open();
        ServiceHost hostA2 = new ServiceHost(typeof(A2_NS.A2));
        hostA2.Open();
        Console.WriteLine("Hit any key to exit...");
        Console.ReadLine();
        hostA1.Close();
        hostA2.Close();
    }
}

我希望我的 WCF 客户端能够调用这两个类:

客户端.cs:

namespace Client_NS
{
    class Program
    {
        static void Main(string[] args)
        {
            B myB = new B();
            A1 a1 = new A1();
            A2 a2 = new A2();
            A1.Do(myB);
            A2.Do(myB);
        }
    }
}

没运气 ;-(

我尝试在我的 WCF-Service app.config中放置 2 个元素:

<service name="A1_NS.A1" >
    <endpoint address="http://localhost/A1"
              contract="IA_NS.IA" />
</service>
<service name="A2_NS.A2" >
    <endpoint address="http://localhost/A2"
              contract="IA_NS.IA" />
</service>

运行调试器时 - 调试应用程序(WCF 服务主机)让我测试两个类的 Do() 方法。

我无法让我的客户这样做。我为这两个服务添加了服务参考。是客户端 app.config 还是我误解了什么?

4

2 回答 2

1

您可以实现部分类,允许您在单独的 cs 文件中分离内容,同时维护单个接口和端点。这不是最理想的方式,因为归根结底它仍然是由部分类组成的单个类,但至少它在您的文件结构中看起来像它,因此提供了一些分离而不是大量的类文件.

示例结构:

IMyService.cs

[ServiceContract]
public interface IMyService
{
   [OperationContract]
   string GenericMethod()

   [OperationContract]
   string GetA(int id)

   [OperationContract]
   string GetB(int id)

}

我的服务.cs

//Put any attributes for your service in this class file
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public partial class MyService : IMyService
{
  public string GenericMethod() 
  {
     return "";
  }
}

AService.cs

public partial class MyService
{
    public string GetA(int id) 
    {
       return "";
    }
}

BService.cs

public partial class MyService
{
      public string GetB(int id) 
      {
          return "";
      }
}
于 2014-03-19T15:20:37.673 回答
0

我看到合同两次(在A2_NS.A2服务标签下),是错误的还是真的存在,然后删除第二个(在结束端点标签之后),看看这是否与您遇到的问题有关?

contract="IA_NS.IA" />
    contract="IA_NS.IA" />
于 2013-09-12T12:46:44.817 回答