I am using asp.net core
along with Entity Framework Core
. My scenario here is, I want to change the connection string at runtime based on Htt
I have resolved this issue by doing change as Guru Stron's comment and subsequent changes. Here is my change.
Step 1: Changed Autofac Registration class as below:
public class DependencyRegistrar : IDependencyRegistrar
{
public virtual void Register(ContainerBuilder builder)
{
//Removed this code
//builder.RegisterType(typeof(DbContextOptionsFactory))
// .As(typeof(IDbContextOptionsFactory))
// .InstancePerRequest();
//Added this code
builder.Register(c => c.Resolve<IDbContextOptionsFactory>().Get())
.InstancePerDependency(); // <-- Changed this line
builder.RegisterType<AppDbContext>()
.As(typeof(IDbContext))
.WithParameter(
new ResolvedParameter(
(pi, cc) => pi.Name == "options",
(pi, cc) => cc.Resolve<IDbContextOptionsFactory>().Get()))
.InstancePerDependency(); // <-- Added this line
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerDependency(); // <-- Changed this line
}
}
Now, if you getting the error:
InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
By add below code in AppDbContext
class to resolve above error.
Step 2: Modified AppDbContext
(Added OnConfiguring()
method)
public class AppDbContext : DbContext, IDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
Assembly assemblyWithConfigurations = typeof(IDbContext).Assembly;
builder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
//Added this method
protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder)
{
base.OnConfiguring(dbContextOptionsBuilder);
}
//..
//..
}