Home » Articles | WCF

Initialize a WCF Service without App.config

1. October 2008 by Juliën Hanssens 0 Comments

Sometimes you just can't stand looking at xml anymore. Sometimes you curse the day someone thought out the concept of configuration files. Sometimes you just want to quickly and easy write some oneliners.

It is at these times that you'd might like the following snippet which allows you to initialize a WCF service through codebehind:

static void Main()
{
 
    // Define the ServiceAddress - by CODE (not by .config):
    string epAddress = "http://localhost:8731/Design_Time_addresses/MyCustomerService";
 
    // Initialize the service - by CODE (not by .config):
    ICustomer customerClient = ChannelFactory<ICustomer>.CreateChannel(new WSHttpBinding(), new EndpointAddress(epAddress));
 
    try
    {
        // Run any method:
        Customer myCustomer = customerClient.Retrieve(1000);
 
        // All is well:
        Console.WriteLine("The name of the customer is: " + myCustomer.DisplayName);
 
    }
    catch (Exception ex)
    {
        Console.WriteLine("Something is wrong with the world today:\n{0}", ex.Message);
    }
 
    Console.ReadLine();
}

Ofcourse, hardcoded references in your project like this are not a good thing. But it's possible to do so - and therefor sometimes desirable.

Comments are closed