The Grayzone

Abstract Class to Dynamically Alter EntityFramework Domain Service Connection

In my previous post I wrote about overriding the LinqToEntitiesDomainService.CreateObjectContext() method to dynamically set the connection string for the used by the domain service.

I realised that I would be using this in a couple of different services in my current project and potentially use it in the future so I wrote a generic abstract class to enable me to do this.

The Class

using System;
using System.Data.Objects;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Server;

public abstract class DomainServiceBase <TContext> : LinqToEntitiesDomainService<TContext>
  where TContext : ObjectContext, new ()
{
  protected override TContext CreateObjectContext()
  {
    // Build up the connection string
    string connection = "connectionString";

    Type contextType = typeof(TContext);
    object objContext = Activator.CreateInstance(contextType, connection);
            
    return objContext as TContext;
  }

  protected override void OnError(DomainServiceErrorInfo errorInfo)
  {
    // Deal with errors
  }
}

You then inherit from this DomainServiceBase class for your Doman Services rather than LinqToEntitiesDomainService.

Key Points

  1. public abstract class DomainServiceBase <TContext> : LinqToEntitiesDomainService<TContext>
      where TContext : ObjectContext, new ()
    

    Generic class inherits from the LinqToEntitiesDomainService class. Constrain the types of objects that can be accepted to anything that inherits from ObjectContext and has a public parameterless constructor.

  2. Type contextType = typeof(TContext);
    object objContext = Activator.CreateInstance(contextType, connection);
    

    Use the Activator class to create an instance of the specified generic type, using the connection string that you have built up as a parameter. This will call the ObjectContext(string) constructor.

  3. return objContext as TContext; Cast the object to the supplied type before returning it.

Share this: