NoPyGod
NoPyGod

Reputation: 5067

Changing entity framework default connection strings used by DbContext at runtime

I have a program using entity framework, and depending on which computer it is run on, it will either connect to a remote database over the network or a local database on the local filesystem.

With entity framework, when I create an instance of MyDbContext (which inherits from entity framework's DbContext) it uses the code first naming conventions and will look in the app.config/web.config for a connection string with the same name (id) as the class -ie.. MyDbContact. Normally this is a very useful convention, but it doesn't suit my particular use case.

When my application loads, and before any querying takes place, I want to set the named connection string to a string of my liking - ie.. a connection string for a remote database or a local one.

Then, all future instances of MyDbContext will automatically obtain my custom connection string.

I do not want to have to hardcode the connection string in the web/app.config.

The program relies heavily on IoC/dependency injection and uses the domain driven design and repository+service patterns, and I also do not want to have to specify the connection string as a parameter to be passed to each repository when registering them with the resolver (autofac).

It seems logical to me that somewhere in the entity framework there must be a place for you to intercept this code first convention of retrieving the connection string from the web.config, and instead just pass in a custom string.

Am I way off, or is there actually a way of changing the default connection strings at runtime?

Upvotes: 1

Views: 1326

Answers (1)

qujck
qujck

Reputation: 14580

One of the constructors of the DbContext class accepts a string, and the string can be the name of a connection string or a connection string.

To handle this using IoC you could define an abstraction to a connection string provider, something like this:

public interface IConnectionStringProvider
{
    string ConnectionString { get; }
}

public class MyContext : DbContext
{
    public MyContext(IConnectionStringProvider connectionStringProvider)
        : base(connectionStringProvider.ConnectionString)
    {
    }
}

public class ConnectionStringProvider : IConnectionStringProvider
{
    public ConnectionStringProvider()
    {
    }

    private string _connectionString = null;
    public string ConnectionString
    {
        get
        {
            if (_connectionString == null)
            {
                //initialise the connection string
                _connectionString = "Data Source=.;Initial Catalog ...";
            }
            return _connectionString;
        }
    }
}

Upvotes: 5

Related Questions