向Autofac注册使用IDesignTimeDbContextFactory

时间:2018-10-09 08:45:31

标签: c# entity-framework-core autofac

我想向Autofac注册OrderContext,但是OrderContext使用IDesignTimeDbContextFactory,而Autofac执行失败。错误是下一个:

  

无法解析参数   “ Microsoft.EntityFrameworkCore.DbContextOptions 1[...OrderContext] options' of constructor 'Void .ctor(Microsoft.EntityFrameworkCore.DbContextOptions 1 [... OrderContext])”。   在   Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(IComponentContext   上下文,IEnumerable 1 parameters) at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1个参数)位于   Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1   参数)

Autofac配置:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterType<OrderContext>()
        .InstancePerDependency();
}

OrderContext是下一个:

public class OrderContext : DbContext
{
    public DbSet<Order> Orders { get; }

    public OrderContext(DbContextOptions<OrderContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new OrderEntityTypeConfiguration());
    }
}

public class OrderContextDesignFactory : IDesignTimeDbContextFactory<OrderContext>
{
    public OrderContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<OrderContext>()
            .UseSqlServer(
                "...");

        return new OrderContext(optionsBuilder.Options);
    }
}

0 个答案:

没有答案