我正在使用带有代码优先迁移的实体框架 5。我有一个DataStore
派生自的类DbContext
:
public class DataStore : DbContext, IDataStore
{
public int UserID { get; private set; }
public DataStore(int userId, string connectionString) : base(connectionString)
{
UserID = userId;
}
public virtual IDbSet<User> Users { get; set; }
// Rest of code here
}
还有一个创建类实例的工厂DataStore
类:
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();
}
}
这些类的构造函数参数在运行时使用Unity注入。到目前为止一切顺利,一切正常!
当我们开始迁移时,问题就出现了:因为我的DataStore
上下文类没有默认构造函数,所以我需要提供一个实现,IDbContextFactory<T>
以便 Code First Migrations 可以实例化它:
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");
}
}
问题是我不知道如何将连接字符串注入这个类。我不能用这样的连接字符串参数创建一个新的构造函数:
public class MigrationDataStoreFactory : IDbContextFactory<DataStore>
{
public string _connectionString { get; set; }
public MigrationDataStoreFactory(string connectionString)
{
_connectionString = connectionString;
}
public DataStore Create()
{
return new DataStore(0, new DateTimeProvider(() => DateTime.Now), _connectionString);
}
}
如果这样做,我会在运行时收到迁移引发的以下异常:
[InvalidOperationException: The context factory type 'MigrationDataStoreFactory' must have a public default constructor.]
System.Data.Entity.Infrastructure.DbContextInfo.CreateActivator() +326
System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo) +106
System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType) +52
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext) +202
System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration) +66
System.Data.Entity.MigrateDatabaseToLatestVersion`2.InitializeDatabase(TContext context) +50
// Truncated stack trace, but you get the idea
除此之外,这个类无论如何都不会被 Unity 实例化。它似乎只是按惯例被 Code First Migrations 以某种方式调用,所以即使我能做到这一点,它也无济于事......
如果我在该方法中对连接字符串进行硬编码,一切正常,但出于显而易见的原因,我不想这样做。
有人可以帮忙吗?