How do I inject a connection string into an instance of IDbContextFactory?
I'm using Entity Framework 5 with Code First Migrations. I have a
DataStore class which derives from DbContext:
public class DataStore : DbContext, IDataStore
{
public int UserID { get; private set; }
public DataStore(int userId, string connectionString) :
base(connectionString)
{
UserID = userId;
_dateProvider = dateProvider;
}
public virtual IDbSet<User> Users { get; set; }
// Rest of code here
}
And a factory class which creates instances of the DataStore class:
public class DataStoreFactory : Disposable, IDataStoreFactory
{
private DataStore _database;
private int _userId;
private string _connectionString;
public DataStoreFactory(int userId, string connectionString)
{
_userId = userId;
_connectionString = connectionString;
}
public IDataStore Get()
{
_database = new DataStore(_userId, _connectionString);
return _database;
}
protected override void DisposeCore()
{
if (_database != null) _database.Dispose();
}
}
These classes have their constructor parameters injected at runtime with
Unity. So far so good, everything works great!
The problem arises when we get to migrations: because my DataStore context
class doesn't have a default constructor, I need to supply an
implementation of IDbContextFactory<T> so that Code First Migrations can
instantiate it:
public class MigrationDataStoreFactory : IDbContextFactory<DataStore>
{
public DataStore Create()
{
// Need to inject connection string so we can pass it to this
constructor
return new DataStore(0, "CONNECTION_STRING_NEEDED_HERE");
}
}
The issue is that I can't figure out how I can inject the connection
string into this class. I can't create a new constructor with a connection
string parameter; if I do I get:
The context factory type 'MigrationDataStoreFactory' must have a public
default constructor.
Everything works fine if I hard-code the connection string in that method,
but I don't want to do that, for obvious reasons.
Can anyone help please?
No comments:
Post a Comment