views:

70

answers:

2

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.

+3  A: 

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.

marc_s
I thought of that - just putting it in the AppSettings, but I figured there must be a more "framework-centric" method for approaching this.I'll wait a bit to see if anyone else chimes in with a better approach before accepting your answer, but this might be it.
camainc
A: 

If you are working with a Silverlight app you can access the Uri of the xap with application.current.host
Then you can add a relative Uri to get the service Uri:

Uri base = application.current.host; Uri relService = new Uri("..\someservice.svc", System.UriKind.Relative);

Uri service = new Uri(base, relService); DataServiceContext svc = new DataServiceContext(service);

Ozan