Autofac ResolvedParameter/ComponentContext not working

后端 未结 1 1794
春和景丽
春和景丽 2020-12-21 19:30

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

相关标签:
1条回答
  • 2020-12-21 20:05

    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);
        }
    
        //..
        //..
    }
    
    0 讨论(0)
提交回复
热议问题