0

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?

3

2 Answers 2

2

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
{

}
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.