问题
I have a DbContext
:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
Now, what if I want to be able to use another DbConfigurationType
, according to AppSettings value?
So that, I change AppSettings value from MySQL
to MSSQL
and it becomes:
[DbConfigurationType(typeof(MsSqlEFConfiguration))]
public class MyDbContext : DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
Of course, I can create a factory, and use reflection to create a new class with custom attribute. However, is there a solution without reflection?
回答1:
I have solved the problem by inheriting from DbConfigurationTypeAttribute
:
public class BaseEfConfiguration : DbConfigurationTypeAttribute
{
public BaseEfConfiguration() : base(SqlConfiguration)
{
}
public static Type SqlConfiguration
{
get
{
string databaseTypeName = ConfigurationManager.AppSettings["DatabaseType"];
switch (databaseTypeName)
{
case "MySQL":
return typeof(MySqlEFConfiguration);
case "MSSQL":
return typeof(MsSqlEFConfiguration);
default:
throw new NotImplementedException($"No such SQL configuration type {databaseTypeName}");
}
}
}
}
[BaseEfConfiguration]
public class BaseDbContext : DbContext
{
}
回答2:
You can replace the attribute with the registration at runtime intercepting the configuration before it's locked:
DbConfiguration.Loaded += (_, a) =>
{
a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s));
a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s));
};
Source
来源:https://stackoverflow.com/questions/38327909/how-to-choose-dbconfigurationtype-programmatically