Explore ways to work with a WCF service programmatically without the service configuration files WCF (Windows Communication Foundation) is a secure, reliable, and scalable messaging platform for developing services in .Net. In WCF, you have a unified programming model that you can leverage for building scalable, robust services. It enables you to configure your services either using configuration files or by using code, i.e., programmatically using C# or VB.Net. Configuring a WCF service has been a pain primarily because of the tedious configuration metadata that you would need to specify to get your WCF service up and running. You can configure your WCF service either using the service configuration files (these are xml files) or by writing code. Since there is no support for debugging configuration files, you can configure your service programmatically as well. Creating a WCF service To get started, let’s create a new WCF service. To create a new WCF service, follow these steps. Open Visual Studio IDE Click on Start -> File -> New -> Project Select WCF from the list of the project templates displayed Specify a name for your WCF service project Click OK to save your WCF service project To configure a WCF service you can simply define a static method called Configure. This method should be defined in the service implementation class as shown below. public class TestService : ITestService { public static void Configure(ServiceConfiguration config) { ServiceEndpoint serviceEndpoint = new ServiceEndpoint(new ContractDescription("ITestService"), new BasicHttpBinding(), new EndpointAddress("basic")); serviceEndpoint.Behaviors.Add(new IDGCustomEndpointBehavior()); config.AddServiceEndpoint(serviceEndpoint); config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true }); config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); } public string GetMessage() { return "Hello"; } } Hosting the WCF service programmatically The following code listing shows how you can configure a WCF service and start it using BasicHttpBinding. As you can see in the code listing given below, the service has been configured programmatically and then started. var serviceUrl = "http://localhost:9000/TestService.svc"; ServiceHost serviceHost = null; try { var uri = new Uri(serviceUrl); serviceHost = new ServiceHost(typeof (TestService), uri); var serviceMetadataBehavior = new ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); serviceHost.AddServiceEndpoint(typeof (IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); var basicHttpBinding = new BasicHttpBinding(); serviceHost.AddServiceEndpoint(typeof (ITestService), basicHttpBinding, serviceUrl); serviceHost.Open(); Console.WriteLine("Service started... " + serviceUrl); } catch (Exception ex) { serviceHost = null; Console.WriteLine("Error starting service" + ex.Message); } finally { if (serviceHost != null) if (!(serviceHost.State == CommunicationState.Closed)) serviceHost.Close(); serviceHost = null; } When you execute the above code listing, the service gets started at the port mentioned in the service url. To verify that the service is working, open a web browser in your system and browse the service’s debug page at https://localhost:9000/TestService.svc Note that ServiceMetadataBehavior is used to configure the service metadata and other related information. An instance of ServiceMetadataBehavior is added to the Behaviors collection using this code snippet: serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); To use the binding of your choice, you should leverage the appropriate binding class, i.e., BasicHttpBinding, NetTcpBinding, etc. Once all service configuration has been defined, you should make a call to the Open method of the ServiceHost instance to start your service. If you would like to use TcpBinding to host your service, you can use the following code. string serviceUrl = "net.tcp://localhost:9000/TestService/"; ServiceHost serviceHost = null; try { Uri uri = new Uri(serviceUrl); serviceHost = new ServiceHost(typeof(TestService), uri); NetTcpBinding netTcpBinding = new NetTcpBinding(); ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior(); serviceHost.Description.Behaviors.Add(serviceMetadataBehavior); serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); serviceHost.AddServiceEndpoint(typeof(ITestService), netTcpBinding, serviceUrl); serviceHost.Open(); Console.WriteLine("Service started... " + serviceUrl); } catch (Exception ex) { serviceHost = null; Console.WriteLine("Error starting service" + ex.Message); } finally { if (serviceHost != null) if (!(serviceHost.State == CommunicationState.Closed)) serviceHost.Close(); serviceHost = null; } If there is any error in starting the service, an exception is thrown and the appropriate message is displayed using the catch block. The finally block has been used to dispose the ServiceHost instance if it is non null. If your service is REStful, you would need to leverage WSHttpBinding as shown below. var serviceUrl = "http://localhost:9000/TestService"; ServiceHost serviceHost = null; try { var uri = new Uri(serviceUrl); serviceHost = new ServiceHost(typeof(TestService), uri); WSHttpBinding wsHttpBinding = new WSHttpBinding(); wsHttpBinding.MaxReceivedMessageSize = 999999; wsHttpBinding.MessageEncoding = WSMessageEncoding.Text; serviceHost.AddServiceEndpoint(typeof(ITestService), wsHttpBinding, string.Empty); ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior(); serviceBehavior.HttpGetEnabled = true; serviceHost.Description.Behaviors.Add(serviceBehavior); serviceHost.Open(); Console.WriteLine("Service started... " + serviceUrl); } catch (Exception ex) { serviceHost = null; Console.WriteLine("Error starting service" + ex.Message); } finally { if (serviceHost != null) if (!(serviceHost.State == CommunicationState.Closed)) serviceHost.Close(); serviceHost = null; } You should create a channel factory instance before you can invoke the methods of the service. Here’s how you can achieve this. BasicHttpBinding basicHttpBinding = new BasicHttpBinding(); var serviceUrl = "http://localhost:9000/TestService"; var endpoint = new EndpointAddress(serviceUrl); var channelFactory = new ChannelFactory<ITestService>(basicHttpBinding , endpoint); ITestService service = channelFactory.CreateChannel(endpoint); If you are using TCP binding, here’s how you can achieve this. NetTcpBinding netTcpBinding = new NetTcpBinding(); string serviceUrl = "net.tcp://localhost:9000/TestService/"; var endpoint = new EndpointAddress(serviceUrl); var channelFactory = new ChannelFactory<ITestService> (netTcpBinding , endpoint); ITestService service = channelFactory.CreateChannel(endpoint); You are now all set to start consuming your service methods. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos