Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide an implementation of IDbContextFactory. But where?

I am trying to run migrations with custom DbContext.

var migrationConfiguration = new DbMigrationsConfiguration { AutomaticMigrationsEnabled = true };
migrationConfiguration.ContextType = typeof(DataContext);
var migrator = new DbMigrator(migrationConfiguration);
migrator.Update();

This throws Migration Exception, because DataContextdoes not implement parameterless constructor:

The target context 'System.Data.Entity.DbContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.

The DataContextconstructor requires parameters, but I already have IDbContextFactory<DataContext> created. How do I tell DbMigrator, to use existing implementation of IDbContextFactory<DataContext>?

like image 988
roslav Avatar asked May 27 '16 12:05

roslav


1 Answers

The IDbContextFactory<> has be in same assembly and provide parameterless constructor.

Another way is to inherit DbConfiguration and set factory in parameterless constructor of derived class (I'm using MEF to get class derived from IDbContextFactory):

public class DataContextConfiguration : DbConfiguration
{
    public DataContextConfiguration()
    {
        SetContextFactory(() => (DataContext)new CompositionManager().Container.GetExportedValue<IDataContextFactory>().Create());
    }
}
like image 82
roslav Avatar answered Nov 15 '22 07:11

roslav