An elegant way to instantiate an odata DataServiceContext

Introduction

When you create an Odata connection,  you need to instantiate a DataServiceContext for which you created first a service reference. There are several ways to do this. We’ll try to find the most optimal way.

Approach 1

DepartmentServiceDataReference.DepartmentServiceData _service
 = new DepartmentServiceData(new Uri("http://localhost:33255/DepartmentServiceData.svc"));

The problem here is both the service address and the port. This approach is far from optimal because you need a mechanism to set the runtime address and port.

Approach 2

 Uri uri = new Uri(Application.Current.Host.Source, "../DepartmentServiceData.svc");
            _service =
                new DepartmentFlatTreeServiceDataReference.DepartmentServiceData(uri);

This is already better because we use the address of the “current host”. The only thing left is to get rid of the magic string “../DepartmentServiceData”.

Approach 3

We first make a small helper method:

private T GetServiceInstance<T>() where T : DataServiceContext
        {
            string serviceName = typeof(T).Name;

            Uri uri = new Uri(Application.Current.Host.Source, "../" + serviceName + ".svc");

            return Activator.CreateInstance(typeof(T), uri) as T;
        }

As you can see, there are no magic strings involved any longer:

DepartmentServiceDataReference.DepartmentServiceData _service = GetServiceInstance<DepartmentServiceDataReference.DepartmentServiceData>();

As we would say here: “Simple comme bonjour” :)