WCF学习(2) ServiceHost寄宿多个服务
WCF在实际应用中,通常都会寄宿多个服务。网上的做法通常有2种:
1. 将服务协定实现在一个类里面,利用partial将实现分散到多个文件,然后添加多个终结点,只需要开启一个ServiceHost.
2. 每个服务开启一个ServiceHost,这种做法在实际实现上也会有所不同,比如可以需要调用某个服务的时候再去开启,利用线程锁来控制同时开启的服务数,或者一次开启所有的服务.
实例1.将服务协定实现在一个类里面,然后添加多个终结点
- 服务协定
[ServiceContract]
public interface IUserService
{
[OperationContract]
string UpdateUser(string json);
[OperationContract]
string UpdateUserList(string json);
[OperationContract]
string GetAllUser(string json);
[OperationContract]
string GetUserByName(string json);
[OperationContract]
string AddUser(string json);
[OperationContract]
string AddUserList(string json);
[OperationContract]
string DeleteUser(string json);
}
省略了ISysConfigService
- 服务实现
省略了SysConfigService
- 服务端启动WCF服务代码
try
{
NetTcpBinding bind = new NetTcpBinding();
bind.Security.Mode = SecurityMode.None;
bind.MaxReceivedMessageSize = 2147483647;
Uri baseAddress = new Uri(string.Format("net.tcp://{0}:{1}/Service", HostIP, 8000));
if (host == null)
host = new ServiceHost(typeof(ServiceImp), baseAddress);
host.AddServiceEndpoint(typeof(ISysConfigService), bind, "SysConfigService");
host.AddServiceEndpoint(typeof(IUserService), bind, "UserService");
if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
ServiceMetadataBehavior sb = new ServiceMetadataBehavior();
sb.HttpGetEn