How to work with a WCF service programmatically (2024)

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.

  1. Open Visual Studio IDE
  2. Click on Start -> File -> New -> Project
  3. Select WCF from the list of the project templates displayed
  4. Specify a name for your WCF service project
  5. 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()

}

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.

How to work with a WCF service programmatically (2024)
Top Articles
Formation architecte d'intérieur | Ecole Esail
Dairyland Auto Insurance Review 2024: Pros and Cons - NerdWallet
Miramar Water Utility
Mensenlinq: Overlijdensberichten zoeken in 2024
Promiseb Discontinued
Memphis Beauty 2084
Ucf Net Price Calculator
Hangar 67
Megan Thee Stallion, Torrey Craig Seemingly Confirm Relationship With First Public Outing
Vonage Support Squad.screenconnect.com
Comparing Each Tacoma Generation, Which is Best?
Erika Henriquez-Quallo
Jacy Nittolo Ex Husband
Central Nj Craiglist
The Courier from Waterloo, Iowa
Bbaexclusive
Reforge Update – Which Reforges Are The Best? – Hypixel Skyblock - Sirknightj
Vegamovies 2023 » Career Flyes
洗面台用 アクセサリー セットの商品検索結果 | メチャ買いたい.com
Pear Shaped Rocsi
Shs Games 1V1 Lol
Rachel Zoe first outing hours after announcing shock marriage split
Envy Nail Bar Memphis
Class B Permit Jobs
Jeep Graphics Ideas
Louisiana Funeral Services and Crematory | Broussard, Louisiana
Sharkbrew
Fedex Express Ship Center
Toonily.cim
85085 1" Drive Electronic Torque Wrench 150-1000 ft/lbs. - Gearwrench
Circuit Court Peoria Il
Used Fuel Tanks For Sale Craigslist
Creator League Standings
Distance To Indianapolis
Family Naturist Contest
charleston rooms & shares - craigslist
Wlox Jail Docket
Broussard’s Mortuary Major Dr.
Black Myth Wukong All Secrets in Chapter 6
Nycda Login
Enlightenment Egg Calculator
Omari Lateef Mccree
Babyboo Fashion vouchers, Babyboo Fashion promo codes, Babyboo Fashion discount codes, coupons, deals, offers
Mercy Baggot Street Mypay
What Is TAA Trade Agreements Act Compliance Trade Agreement Act Certification
Research Tome Neltharus
Thoren Bradley Lpsg
Arre St Wv Srj
Minecraft Skin Tynker
Reli Stocktwits
Trivago Anaheim California
A Man Called Otto Showtimes Near Cinemark Palace 20
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6043

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.