Windows服务无法正常工作

时间:2014-08-29 13:57:36

标签: c# .net windows wcf service

我准备了一个带有WCF服务库和Windows服务的应用程序。我已经在代码项目的this link的帮助下完成了整个过程。

创建WCF的所有功能后,它成功构建并创建了WCF DLL文件。现在,我在同一个解决方案资源管理器中创建了Windows服务项目,用于托管服务DLL。在OnStart方法中,我编写了以下代码:

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        ServiceHost sHost;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            sHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
            sHost.Open();
        }

        protected override void OnStop()
        {
            sHost.Close();
        }
    }
}

为了添加WcfServiceLibrary1,我在此服务中添加了WCF DLL的引用。为此,右键单击 Solution Explorer 中的项目,然后选择添加引用。要在引用中添加DLL,请在出现的窗口中选择“浏览”选项卡,然后导航到我们的WCF服务库所在的文件夹。在该位置,DLL可以在“bin \ Release”文件夹中找到。

添加引用后它没有出错,但是当我要构建解决方案时,它会出现以下错误:

  

找不到类型或命名空间名称'WcfServiceLibrary1'(您是否缺少using指令或程序集引用?)

我再次添加了引用,错误消失了,然后我再次构建了解决方案。出现了相同的错误消息。

我无法理解为什么会这样。即使我已经完全按照链接并从头开始再次准备解决方案,但每次都会出现相同的错误消息。

以上问题现已通过关注toadflakz的答案得到解决。现在,我的服务已正确安装,但在 OnStart上获得以下异常。

Service cannot be started. System.InvalidOperationException: Service 'WcfServiceLibrary1.WCFService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
   at System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreApplicationEndpoints(ServiceDescription description)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

我尝试了很多选项,我真的很挣扎。请帮我摆脱这个,这样我才能成功开始我的服务。

1 个答案:

答案 0 :(得分:1)

Visual Studio没有获取WcfServiceLibrary1项目与Windows服务项目之间的依赖关系。您已链接到DLL而不是项目,因此在Windows服务项目需要引用它进行编译之前,VS不知道它需要构建WcfServiceLibrary1输出。

构建解决方案时,所有先前的输出(包括DLL)都将作为构建的Clean阶段的一部分被删除。这就是构建Windows服务项目时无法找到WcfServiceLibrary1.dll的原因。

纠正这种情况的方法是针对项目而不是DLL构建。

在Visual Studio中:右键单击并选择“添加引用” - >选择项目标签 - >选择“WcfServiceLibrary1”项目 - >单击“添加引用”。