【问题标题】:The type or namespace"ServiceHost" could not be found in my console app在我的控制台应用程序中找不到类型或命名空间“ServiceHost”
【发布时间】:2019-08-01 23:17:34
【问题描述】:

我正在尝试在控制台应用程序中实现自托管 WCF 服务。第一步是我尝试先实现一个 helloworld 应用程序。但是,似乎我无法引用 System.ServiceModel 中的关键字或类。谁能告诉我我做错了什么?下面是我的代码。现在找不到关键字“ServiceHost”。

using System;
using System.ServiceModel;

namespace selfHost
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }

public class HelloWorldService : IHelloWorldService
{
    public string SayHello(string name)
    {
        return string.Format("Hello, {0}", name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Uri baseAddress = new Uri("http://localhost:8080/hello");

        // Create the ServiceHost.
        using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
        {
            // Enable metadata publishing.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            // Open the ServiceHost to start listening for messages. Since
            // no endpoints are explicitly configured, the runtime will create
            // one endpoint per base address for each service contract implemented
            // by the service.
            host.Open();

            Console.WriteLine("The service is ready at {0}", baseAddress);
            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();

            // Close the ServiceHost.
            host.Close();
        }
    }
}

}

【问题讨论】:

  • 这是一个意外行为。 ServiceHost 似乎是一个非常古老的东西,一直追溯到 Framework 1.1 和整个 Core。所以我们必须寻找更难调试的情况:也许解析出错了,它甚至不能告诉你哪里有错误了?还有其他编译器错误吗? |您是否将正确的 .dll 添加到项目参考中。我怀疑大多数控制台应用程序默认添加 System.ServiceModel.dll。但是,它应该已经在 using 指令上抱怨了。 |也许这是 Visual Studio 中的一个错误。毕竟它也是一个程序。
  • 您是否尝试过使用 System.ServiceModel.ServiceHost 的完全限定名称?
  • 嗨@Christopher 我也尝试了完全限定名称,但它仍然有相同的编译错误。
  • 这会在源代码中留下一个一般错误——我在这里看不到——它严重影响了解释,它无法告诉你它在哪里出错。或者IDE中的一些错误。应该有一种方法可以对项目进行干净的重建,只是为了摆脱任何可能损坏并导致此问题的临时数据。

标签: c# visual-studio console-application self-hosting


【解决方案1】:

.Net Core 不再支持此功能。在看:https://github.com/dotnet/wcf/issues/2559

如果可以的话,您可以降级到 .Net 框架,或者使用另一个第三方库作为服务主机。

【讨论】:

    【解决方案2】:

    根据你的代码,我用.NET框架做了一个demo,没有发现任何错误,但是如果你用的是.NET Core,就不行了,你有没有试过重新引用系统服务模型? 有一个关于 System.ServiceModel References 的链接,希望它对你有用。 System.ServiceModel References

    【讨论】:

    • 这不是在回答问题,而是作为评论来获取更多信息。
    猜你喜欢
    • 2012-01-23
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    相关资源
    最近更新 更多