无法创建MyDbContext类型的对象

时间:2020-10-07 16:08:58

标签: c# autofac entity-framework-migrations

我正在使用Autofac注册MyDbContext,并且工作正常,但是当我尝试使用任何ef迁移命令(例如Add-Migration -Name my-migration)时,都会收到错误消息:

无法创建类型为“ MyDbContext”的对象。有关设计时支持的不同模式,请参见streaming

如果我向MyDbContext注册IServiceCollection,该错误就会消失。我的Autofac配置是:

builder.Register(
    _ =>
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        var conn = configuration.GetConnectionString(connName);
        var dbConnection = new NpgsqlConnection(conn);
        var password = configuration.GetPassword(connName);

        dbConnection.ProvidePasswordCallback =
            (host, port, database, username) => password;
        optionsBuilder.UseNpgsql(dbConnection);

        return new MyDbContext(optionsBuilder.Options);
    })
    .AsSelf()
    .InstancePerLifetimeScope();

根据Microsoft的文档:

这些工具首先尝试通过调用Program.CreateHostBuilder(),调用Build(),然后访问Services属性来获取服务提供商。

我调试了应用程序,并能够通过调用MyDbContext获得的IHost激活IHostBuilder.Build()。我想念什么,我还需要做些其他事情吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您是否尝试过提到的here.

解决方案
builder.Register(componentContext =>
    {
        var serviceProvider = componentContext.Resolve<IServiceProvider>();
        var configuration = componentContext.Resolve<IConfiguration>();
        var dbContextOptions = new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>());
        var optionsBuilder = new DbContextOptionsBuilder<TContext>(dbContextOptions)
            .UseApplicationServiceProvider(serviceProvider)
            .UseSqlServer(configuration.GetConnectionString("MyConnectionString"),
                serverOptions => serverOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), null));

        return optionsBuilder.Options;
    }).As<DbContextOptions<TContext>>()
    .InstancePerLifetimeScope();

builder.Register(context => context.Resolve<DbContextOptions<TContext>>())
    .As<DbContextOptions>()
    .InstancePerLifetimeScope();

builder.RegisterType<TContext>()
    .AsSelf()
    .InstancePerLifetimeScope();