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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos