简体   繁体   English

我可以在Windows服务中托管WCF服务吗?

[英]Can I host a WCF Service in a windows service?

I created a WCF project by going to Add New Project -> WCF service library and when I run it on the development environment, it opens up the WCF test client. 我通过添加新项目-> WCF服务库创建了WCF项目,当我在开发环境中运行它时,它将打开WCF测试客户端。 How do I install this service on a server that doesn't have Visual Studio installed (I'd like to not host it on IIS). 我如何在未安装Visual Studio的服务器上安装此服务(我不想在IIS上托管它)。 Should I write a new windows service? 我应该写一个新的Windows服务吗?

Create a Windows Service project. 创建一个Windows服务项目。

Add your WCF Service to this project. 将WCF服务添加到该项目。

In the main Windows Service class (defaults to Service1.cs), add a member: 在主要的Windows Service类(默认为Service1.cs)中,添加一个成员:

internal static ServiceHost myServiceHost = null;

Modify OnStart() to start a new ServiceHost with your WCF Service type: 修改OnStart()以使用WCF服务类型启动新的ServiceHost:

 protected override void OnStart(string[] args)
    {
        if (myServiceHost != null)
        {
            myServiceHost.Close();
        }

        myServiceHost = new ServiceHost(typeof(MyService));
        myServiceHost.Open();
    }

Modify OnStop(): 修改OnStop():

protected override void OnStop()
    {
        if (myServiceHost != null)
        {
            myServiceHost.Close();
            myServiceHost = null;
        }
    }

Add a Setup and Deployment project (Setup Project) to your solution. 将安装和部署项目(安装项目)添加到您的解决方案中。 Set output of that project to be the main output of the Windows Service project. 将该项目的输出设置为Windows Service项目的主要输出。 When you build the Setup and Deployment project, you should see a Setup.exe file that you can use to install the service. 生成安装和部署项目时,应该会看到一个Setup.exe文件,可用于安装服务。

Keep in mind you still need to setup your endpoints and bindings. 请记住,您仍然需要设置端点和绑定。 Look into using nettcpbinding for this setup. 考虑使用nettcpbinding进行此设置。

As a final note, reference: Error 5 : Access Denied when starting windows service if you are experiencing problems when starting the Windows Service after installation. 最后,请参考: 错误5:如果在安装后启动Windows Service时遇到问题,则启动Windows Service时访问被拒绝

You need to create a windows service project and then add reference to your WCF service and host it. 您需要创建Windows服务项目,然后添加对WCF服务的引用并将其托管。 In order to install the service, you do not need visual studio, you need to use installutil.exe . 为了安装该服务,您不需要Visual Studio,需要使用installutil.exe

Have a look here . 在这里看看。

Take a look at the TopShelf library. 看一下TopShelf库。 I've used it to create a number of WCF services. 我用它来创建许多WCF服务。

TIP: If you're planning on writing more WCF services it might be worth your while reading up on port sharing. 提示:如果您打算编写更多的WCF服务,那么阅读端口共享可能是值得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM