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 how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos