How to choose DbConfigurationType programmatically?

强颜欢笑 提交于 2021-02-18 19:34:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!