本文将向大家介绍如何托管内部WCF服务和公共WCF服务,为了托管内部WCF服务,需要建立一个内部端点,并使用内部角色通信,与在输入端点上托管一个外部服务最主要的区别是内部端点不具有负载均衡特性,而输入端点是挂钩在负载均衡器上的,具有负载均衡功能。
托管内部WCF服务
其实要托管一个内部WCF服务很简单,唯一需要注意的是传递给 ServiceHost 的基地址不同,因为端口号和IP地址要等到运行时才知道,因此需要创建一个主机,动态地传递这些信息给它。
undefined
undefined
undefined undefined
public
override bool OnStart()
{
//
设置最大并发连接数
ServicePointManager.DefaultConnectionLimit
=
12
;
DiagnosticMonitor.Start(
"
DiagnosticsConnectionString
"
);
//
For
information
on
handling configuration changes
//
see the MSDN topic at http:
//
go.microsoft.com
/
fwlink
/
?LinkId
=
166357
.
RoleEnvironment.Changing
+=
RoleEnvironmentChanging;
StartWCFService();
return base.OnStart();
}
private
void StartWCFService()
{
var baseAddress
=
String
.Format(
"
net.tcp://{0}
"
,
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[
"
EchoService
"
].IPEndpoint
);
var host
=
new
ServiceHost(typeof(EchoService),
new
Uri(baseAddress));
host.AddServiceEndpoint(typeof(IEchoService),
new
NetTcpBinding(SecurityMode.None),
"
echo
"
);
host.Open();
使用内部WCF服务
我想从我另一个托管的服务调用这个服务,下面就是调用这个服务的所有代码:
undefined
undefined
undefined undefined
protected void Button1_Click(
object
sender, EventArgs e)
{
var factory
=
new
ChannelFactory
<
WorkerHost.IEchoService
>
(
new
NetTcpBinding(SecurityMode.None));
var channel
=
factory.CreateChannel(GetRandomEndpoint());
Label1.Text
=
channel.Echo(TextBox1.Text);
}
private
EndpointAddress GetRandomEndpoint()
{
var endpoints
=
RoleEnvironment.Roles[
"
WorkerHost
"
].Instances
.Select(i
=>
i.InstanceEndpoints[
"
EchoService
"
])
.ToArray();
var r
=
new
Random(DateTime.Now.Millisecond);
return
new
EndpointAddress(
String
.Format(
"
net.tcp://{0}/echo
"
,
endpoints[r.Next(endpoints.Count()
-
1
)].IPEndpoint)
);
}9
7
3
1
2
4
8
: