I am using Entity Framework Code First. I want to be able to insert a System.Data.Common.DbConnection object when creating a context instance that derives from System.Data.Entity.DbContext . This means that I can transfer different types of connections depending on the environment in which the code works, i.e. Use System.Data.SqlClient (SQL Server) in development, System.Data.SQLite for unit testing and something else in the production process. The relevant parts of the Context are as follows:
public class Context : DbContext { public Context(DbConnection dbConnection) : base(dbConnection, true) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>()); base.OnModelCreating(modelBuilder); } public DbSet<Test> Tests { get; set; } }
This gives me the following error: The target context 'Services.Persistence.Context' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory. The target context 'Services.Persistence.Context' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory. I think this happens during model initialization, when the Entity Framework seems to feel that it needs a new native Context , regardless of the IoC pattern I'm trying to achieve. The lack of a default constructor is by design. The IDbContextFactory interface is also useless - it should also have a default constructor.
Is the Entity Framework Code the first completely attached to the idea of โโsetting up its configuration by reading the connection string from the configuration file (or, alternatively, passing the connection string directly), or can I get around this?
UPDATE, here's the Windsor configuration:
container.Register(Component .For<DbConnection>() .UsingFactoryMethod(() => new SqlConnection("Data Source=(localdb)\\v11.0;Database=ThatProject;MultipleActiveResultSets=true")) .LifeStyle.Transient); container.Register(Component .For<Context>() .UsingFactoryMethod(k => new Context(k.Resolve<DbConnection>())) .LifeStyle.PerWebRequest); container.Register(Component .For<IRepository>() .UsingFactoryMethod(k => new Repository(k.Resolve<Context>())) .LifeStyle.PerWebRequest);
source share