【问题标题】:Cannot access ServiceHost methods无法访问 ServiceHost 方法
【发布时间】:2012-02-10 03:28:39
【问题描述】:

我有一个使用我创建的 WCF 服务的 Silverlight 项目。我的问题是,在我的 WCF 服务中,我创建了一个 ServiceHost,但 VS2010 似乎无法识别我的对象实例(在 svHost 下划线)。以下是我的服务的代码。

using System;
using System.Collection.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;

namespace userIO.Web
{
     [ServiceContract]
     public class CoordsService
     {
         [OperationContract]
         public double xDir();
         [OperationContract]
         public double yDir();
         [OperationContract]
         public String keyPressed();

         public class Coords : CoordsService
         {
             public double xDir { get; set; }
             public double yDir { get; set; }
             public String keyPressed { get; set; }
         }

         ServiceHost svHost = new ServiceHost(typeof(Coords), new Uri("http://localhost:8080"));
         BasicHttpBinding binding = new BasicHttpBinding();
         svHost.AddServiceEndpoint(typeof(CoordsService), binding, "");
         svHost.Open();
     }
}

【问题讨论】:

  • 这段代码不能编译——你不能在方法之外有语句。最后两行(AddServiceEndpoint 和 Open)应该会给您一个构建错误。您可以发布正确的代码吗?
  • 我在 SO 上发帖是因为我无法编译它。不知道如何修复这些特定的行。
  • 如果您使用的是 SL 和 VS,您应该添加一个新的“启用 Silverlight 的 WCF 服务”。这将具有可供 SL 使用的服务的样板文件。

标签: c# .net wcf silverlight visual-studio-2010


【解决方案1】:

您的 ServiceContract 应该装饰一个接口(合同)。 ServiceHost 应该托管此接口的一个实例,并且位于它托管的同一服务之外。至少我只看到过这种方式。

基本结构是:

[ServiceContract]
public interface IService
{
     [OperationContract]
     void DoSomething(Data data);
}

[DataContract]
public class Data
{
     [DataMember]
     int Num {get;set;}
}

public class Service : IService
{
    public void DoSomething(Data data)
    {  // do something }
}

// run in any other kind of app, console, win service, winform/wpf
static void Main()
{
         ServiceHost svHost = new ServiceHost(typeof(Service), new Uri("http://localhost:8080"));
         BasicHttpBinding binding = new BasicHttpBinding();
         svHost.AddServiceEndpoint(binding, "");
         svHost.Open();

}

在 VS2010 中启动和运行服务的更简单的解决方案是在新的 WCF 服务模板中创建服务。取出他们的演示代码,为 servicecontract 接口和实现服务放入您自己的代码,然后选择调试 -> 运行,VS2010 将为您托管服务,而无需创建外部应用程序来运行服务。还可以让您向服务发送数据,以在其简单的 winforms 应用程序中测试您的 wcf 函数的代码和返回值。

【讨论】:

  • 感谢您清理 WCF。但是,我仍然可以从 .svc.cs 文件中的类访问 ServiceHosts 吗?
  • 据我所知并在 iis 中托管 WCF 服务,您只想在 svc.cs 中输入有关 iis 托管的服务名称的信息。如果这就是您提到 svc.cs 文件时的意思。
  • 服务和 wcf 的整个概念是将服务托管在使用它的代码/客户端之外的某个地方。这就是 SOA 的重点,工作是在其他地方完成的,在想要使用它的应用程序之外的某个地方。因此,您需要将服务托管在您想要使用的应用程序之外的其他地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 2013-05-03
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多