1、 WCF需要宿主容纳对应的服务,外界才能进行访问。
2、WCF宿主类型
Self-hosting
– 控制台应用程序,Windows应用程序,Windows服务
– HTTP, TCP, named pipes, Microsoft® Message Queuing (MSMQ)IIS/Microsoft® ASP.NET
– HTTP
Windows Activation Service (windows2008/IIS7的新东西)
– HTTP, TCP, named pipes, MSMQ
3、Self-Hosting
ServiceHost实例必须进行初始化来为服务暴露出端点(endpoint)
每个ServiceHost与指定的服务类型(接口)相关联
Self-hosting环境手动创建实例
1)代码配置
ServiceHost host = new ServiceHost(typeof(Service1));
host.AddServiceEndpoint(typeof(IService2), new BasicHttpBinding(), "http://localhost:9000/Service1");
2)配置文件配置
ServiceHost host = new ServiceHost(typeof(Service1));
host.Open();
<service name="ConsoleApplication.Service1">
<endpoint address="http://localhost:9000/Service1"
binding="basicHttpBinding"
contract="ConsoleApplication.IService1" />
</service>
3)多服务
ServiceHost host1 = new ServiceHost(typeof(Service1));
ServiceHost host2 = new ServiceHost(typeof(Service2));
host1.Open();
host2.Open();
<system.serviceModel>
<services>
<service name="ConsoleApplication.Service1">
<endpoint address="http://localhost:9000/Service1"
binding="basicHttpBinding"
contract="ConsoleApplication.IService1" />
</service>
<service name="ConsoleApplication.Service2">
<endpoint address="http://localhost:9000/Service2"
binding="basicHttpBinding"
contract="ConsoleApplication.IService2">
</endpoint>
</service>
</services>
</system.serviceModel>
4)ServiceHost事件
//– Opening, Opened,Closing, Closed,Faulted, UnknownMessageReceived
ServiceHost host = new ServiceHost(typeof(Service1));
host.Opening+= new EventHandler(OnOpening);
host.Opened += new EventHandler(OnOpened);
host.Closing += new EventHandler(OnClosing);
host.Closed += new EventHandler(OnClosed);
host.Faulted += new EventHandler(OnFaulted);
host.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(OnUnknownMessageReceived);
static void OnOpening(object sender, EventArgs e)
{
Console.WriteLine("service opening");
}
4、IIS/WAS宿主
IIS/WAS 端点与.svc文件相关联
对于传统的IIS来说,如果WCF用它来做宿主,那么只支持Http的binding。
对于传统的IIS作为宿主有一个好处,就是当客户端发起一个请求,每个不同的请求会在同一服务进程的不同Domain里处理,也就是说如果一个恶意的攻击成功了,他只会影响到某一个App Domain,其他的Domain不会受到影响仍然可以正常工作,服务本身的进程也不会受到影响、那些运行的dll也不会受到影响,这是IIS和.Net Framework的运行方式决定的,是特性。如果用命令行窗口程序的话,一旦恶意攻击成功,那么整个服务就用可能完全瘫痪。
WAS(Windows Process Activation Service):他扩展出了不同Binding的监听器和接口,所以它可以适应更多的通信方式。IIS7中才支持。
5、Windows应用程序
通常用于在客户端安装,来控制WCF服务的开启和关闭
1)Windows应用程序
• Windows® Forms 或者WPF
• 从客户端主机暴露服务
• 需要对上下文同步有所认识
– UI线程或者其他线程
• 值得注意:
– ServiceHost需要手动打开
–判断服务是否需要上下文同步
2)Windows应用程序
• 如果ServiceHost在非UI线程上打开,服务操
作会在新线程上进行操作
• 如果在UI线程上调用,服务会自动加入到该线
程上,除非UseSynchronizationContext
设置为false
– 可配置的服务行为(service behavior)
6、Windows服务宿主
• 用于无人值守的服务器主机
• 也可以部署在客户端主机
– 需要对Windows服务进行额外的配置
• 当主机启动时,宿主环境初始化,如果发生错误可以重新启动
• 打开与关闭Windows服务时,ServiceHost实例也会被打开与关闭
7、宿主的应用场景
• 在每个平台上选择不同类型的宿主
• Windows Server® 2003
– 在IIS 6上应用HTTP协议
– 在Windows服务上应用non-HTTP
• Windows Server® 2008(Longhorn)
– 在IIS 7/WAS可以应用所有的协议
• Windows® XP Service Pack 2 与Windows Vista®
– 客户端主机运行Windows应用程序,或者Windows服务