Search code examples
wcfwcf-clientwcf-data-servicesodata

How to instantiate a WCF DataServices Client without hard-coding the URI


I'm fairly new to WCF DataServices (OData) and I need to know the best way to instantiate the entity container on the client without hard-coding the URI. It seems like all of the examples on MSDN describe instantiating the client like this:

Uri uri = new Uri("http://www.someservice.svc");
DataServiceContext svc = new DataServiceContext(uri);

However, I know I must be missing something somewhere, because it doesn't make any sense to hard-code a service address like this. For one thing, how do you dynamically change the address when you move from Development to Test to QA to Production, when each environment is likely to have a different URI?

Thanks for any insights into this.


Solution

  • Put your DataService URL into e.g. your Settings file or just plain app.config:

    Uri uri = new Uri(ConfigurationManager.AppSettings["ServiceURI"]);
    DataServiceContext svc = new DataServiceContext(uri);
    

    And in your app.config (or web.config for a web app):

    <appSettings>
      <add key="ServiceURI" value="http://www.someservice.svc" />
    </appSettings>
    

    Or grab it from a database config table..... or or or or or..... plenty of choices!

    The URI is just a string - you can grab that from just about any configuration source you might have.