简体   繁体   English

WCF:什么是ServiceHost?

[英]WCF: What is a ServiceHost?

As I'm currently learning to use WCF Services, I am constantly encountering tutorials on the internet which mention using a ServiceHost when using a WCF Service. 由于我目前正在学习使用WCF服务,因此我经常遇到互联网上的教程,这些教程在使用WCF服务时提到使用ServiceHost

What exactly is this ServiceHost ? 这个ServiceHost究竟是什么?


In my current project I am using a WCF Service and having a reference to it from my app and whenever I want to consume it from my app I just instantiate its ServiceClient like such: 在我当前的项目中,我正在使用WCF服务并从我的应用程序中引用它,每当我想从我的应用程序中使用它时,我只是实例化它的ServiceClient如下所示:

new MusicRepo_DBAccess_ServiceClient(new InstanceContext(instanceContext), customBinding, endpointAddress);

And then access my web methods ( OperationContract s) from that instance (obviously opening it before consuming the method and closing it afterwards with Open and Close ) 然后从该实例访问我的Web方法( OperationContract s)(显然在使用该方法之前打开它并在之后使用OpenClose

My WCF service is host in my IIS and I just access the .svc from my app to instantiate the ServiceClient . 我的WCF服务是我的IIS中的主机,我只是从我的应用程序访问.svc来实例化ServiceClient

So why and where is ServiceHost used? 那么为什么以及ServiceHost在哪里使用?

A ServiceHost basically provides you everything you need to host a WCF service in a non-IIS or WAS setting. ServiceHost基本上为您提供了在非IIS或WAS设置中托管WCF服务所需的一切。 A common place for a ServiceHost would be in a console app or Windows service. ServiceHost的常见位置是控制台应用程序或Windows服务。 See the example code from MSDN for how to setup a ServiceHost in a console app . 有关如何在控制台应用程序中设置ServiceHost的信息,请参阅MSDN中的示例代码。

Your service implementation is just a .NET class - you need to have a runtime environment for it, so it can be executed somehow. 您的服务实现只是一个.NET类 - 您需要有一个运行时环境,因此它可以以某种方式执行。 That's what the ServiceHost is for - it will load your service class, set up the endpoints and channel listeners and all that stuff, and thus give your service class an "ecosystem" to live and operate in. 这就是ServiceHost的用途 - 它将加载您的服务类,设置端点和通道监听器以及所有这些东西,从而为您的服务类提供一个生态和操作的“生态系统”。

You can either instantiate a ServiceHost class yourself in a console app, a Windows service, or even a Winforms app, and thus make your WCF service class available to the outside world - or you can delegate that work to IIS or WAS. 您可以在控制台应用程序,Windows服务甚至Winforms应用程序中自己实例化ServiceHost类,从而使您的WCF服务类可供外部使用 - 或者您可以将该工作委派给IIS或WAS。 Even IIS or WAS will use a ServiceHost to host your WCF service - they just do it automagically behind the scenes, and "on demand" - whenever a request for your WCF service comes in. 甚至IIS或WAS也将使用ServiceHost来托管您的WCF服务 - 他们只是在幕后自动执行,并且“按需” - 每当您的WCF服务请求进入时。

Marc

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

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