我有DbContext
:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MyDbContext : DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
现在,如果我想根据AppSettings值使用另一个DbConfigurationType
怎么办?
这样,我将AppSettings值从MySQL
更改为MSSQL
,它变为:
[DbConfigurationType(typeof(MsSqlEFConfiguration))]
public class MyDbContext : DbContext
{
public DbSet<MyClass> MyClasses { get; set; }
}
当然,我可以创建一个工厂,并使用反射创建一个具有自定义属性的新类。但是,有没有反思的解决方案吗?
答案 0 :(得分:1)
我通过继承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
{
}
答案 1 :(得分:0)
您可以在运行时使用注册替换属性,在锁定之前拦截配置:
DbConfiguration.Loaded += (_, a) =>
{
a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s));
a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s));
};