Reputation: 6973
I have a Console Application that host a WCF service. Right now I configure the application to run in the following way:
// within my program class
class Program
{
static void Main(string[] args)
{
// retrieve the current URL configuration
Uri baseAddress = new Uri(ConfigurationManager.AppSettings["Uri"]);
Then I start a new instance of a WebServiceHost to host my WCF REST service
using (WebServiceHost host = new WebServiceHost(typeof(MonitorService), baseAddress))
{
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof (IMonitorService), new WebHttpBinding(), "");
ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
stp.HttpHelpPageEnabled = false;
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
So far so good except that now I came up with the requirement of having two WCF services hosted in the following structure
http://localhost:[port]/MonitorService and http://localhost:[port]/ManagementService
Can I add a new service endpoint and distinguish the two endpoints by using a different contract? If yes, the implementation of the two contracts should reside in the same class MonitorService cause it is the one used by the WebServiceHost?
Upvotes: 0
Views: 274
Reputation: 5610
Yes, you can host multiple services in single console application. You can create multiple hosts for multiple services. You can make use of following generic method to start hosts for a given service.
/// <summary>
/// This method creates a service host for a given base address and service and interface type
/// </summary>
/// <typeparam name="T">Service type</typeparam>
/// <typeparam name="K">Service contract type</typeparam>
/// <param name="baseAddress">Base address of WCF service</param>
private static void StartServiceHost<T,K>(Uri baseAddress) where T:class
{
using (WebServiceHost host = new WebServiceHost(typeof(T), baseAddress))
{
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(K), new WebHttpBinding(), "");
ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
stp.HttpHelpPageEnabled = false;
host.Open();
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
// Close the ServiceHost.
host.Close();
}
}
Upvotes: 1