提供服务的主机。
实现 服务模型编程模型所使用的主机。
当您没有使用 Internet 信息服务 (IIS) 或 Windows 激活服务 (WAS) 公开服务时,请使用 ServiceHost 类来配置和公开服务以供客户端应用程序使用。IIS 和 WAS 均代表您与 ServiceHost 对象交互。
若要公开一项服务以供调用方使用, 需要完整的服务说明(由 ServiceDescription 类表示)。 ServiceHost 类根据服务类型和配置信息创建 ServiceDescription,然后再使用该说明为说明中的每个终结点创建 ChannelDispatcher 对象。
使用 ServiceHost 对象加载服务、配置终结点、应用安全设置并启用侦听程序来处理传入的请求。
public static void Main()
{
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
{
try
{
// Open the ServiceHost to start listening for messages.
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
// Close the ServiceHost.
serviceHost.Close();
}
catch (TimeoutException timeProblem)
{
Console.WriteLine(timeProblem.Message);
Console.ReadLine();
}
catch (CommunicationException commProblem)
{
Console.WriteLine(commProblem.Message);
Console.ReadLine();
}
}
}
http://blog.csdn.net/dyllove98/article/details/9631427
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"http://127.0.0.1:1111/CalculatorService");
if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://127.0.0.1:1111/CalculatorService/metadata");
host.Description.Behaviors.Add(behavior);
}
host.Opened += delegate
{
Console.Write("CalculatorService已经启动,按任意键终止服务");
};
host.Open();
Console.Read();
}