WCF绑定netTcpBinding寄宿到IIS
继续沿用上一篇随笔中WCF服务类库 Wettery.WcfContract.Services
服务端
添加WCF服务应用程序 Wettery.WcfIISHost.Services,其中添加两个WCF服务,GameService.svc PlayerService.svc,删掉契约接口和 .cs内嵌文件,只留下.svc文件
我们通过Autofac注入契约/服务的依赖关系,Nuget引用
Install-Package Autofac.Wcf
修改两个svc文件的ServiceHost声明
<%@ ServiceHost Language="C#" Debug="true" Service="Wettery.WcfContract.Services.IGameService, Wettery.WcfContract.Services" Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>
<%@ ServiceHost Language="C#" Debug="true" Service="Wettery.WcfContract.Services.IPlayerService, Wettery.WcfContract.Services" Factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" %>
添加 Global.asax,修改 Application_Start 方法,程序启动时就注入依赖关系
protected void Application_Start(object sender, EventArgs e) { var builder = new ContainerBuilder(); //注册其它依赖关系 //.... //注册WCF服务依赖关系 var wcfAssembly = typeof(GameService).Assembly; builder.RegisterAssemblyTypes(wcfAssembly).AsImplementedInterfaces().AsSelf(); var container = builder.Build(); AutofacHostFactory.Container = container; }
服务端配置
修改Web.config中system.serviceModel节
<system.serviceModel> <services> <service name="Wettery.WcfContract.Services.GameService" behaviorConfiguration="mex"> <endpoint address="" binding="netTcpBinding" contract="Wettery.WcfContract.Services.IGameService" bindingConfiguration="netTcpBindingConfig"></endpoint> <!--为net.tcp绑定提供元数据--> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" /> </service> <service name="Wettery.WcfContract.Services.PlayerService" behaviorConfiguration="mex"> <endpoint address="" binding="netTcpBinding" contract="Wettery.WcfContract.Services.IPlayerService" bindingConfiguration="netTcpBindingConfig"></endpoint> <!--为net.tcp绑定提供元数据--> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" /> </service> </services> <bindings> <netTcpBinding> <binding name="netTcpBindingConfig" transferMode="Buffered" portSharingEnabled="true"> <readerQuotas maxStringContentLength="6553600" /> <security mode="None" /> </binding> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="mex"> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
IIS配置
因为IIS默认不支持非HTTP协议,所以要开启非HTTP功能,“打开或关闭Windows功能”中选中HTTP和非HTTP激活
编译WCF应用程序,在IIS中添加一个站点,指向WCF目录,绑定两个协议,HTTP用21335端口,NET.TCP用21336端口
站点,高级设置中启用net.tcp协议
客户端测试
还是用wcftestclient工具测试,WCF服务元数据地址:
http://localhost:21335/GameService.svc
http://localhost:21335/PlayerService.svc
如果Invoke发生错误
通常是没开启这两个服务,开启即可
Net.Tcp Listener Adapter
Net.Tcp Port Sharing Service