添加迁移:无法创建 AppContext 类型的对象

Add Migration: Unable to create an object of type AppContext

我有一个包含两个项目(DataLayer 和 ServiceLayer)的 .NET 5 解决方案。 在 DataLayer 中,我有以下 DbContext:

internal class ApplicationContext
    : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options)
        : base(options)
    {
    }
    public virtual DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
    }
}

和以下 DbContextFactory:

internal sealed class ContextFactory
    : IDbContextFactory<ApplicationContext>
{
    public ContextFactory(DbContextOptions<ApplicationContext> options)
    {
        Options = options ?? throw new ArgumentNullException(nameof(options));
    }

    private DbContextOptions<ApplicationContext> Options { get; }

    public ApplicationContext CreateDbContext()
    {
        return new ApplicationContext(Options);
    }
}

我在每个存储库 ctor 中使用的:

 public UserRepository(IDbContextFactory<ApplicationContext> contextFactory) { ... }

以及 DbContextFactory 的服务初始化:

services.AddDbContextFactory<ApplicationContext>(options =>
{
    options
    .UseLazyLoadingProxies()
    .UseSqlServer(connectionString);
});

问题是当我尝试创建迁移时收到以下消息:

Unable to create an object of type 'ApplicationContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 for both of commands:

添加迁移初始

dotnet ef migrations add Initial --project DataLayer

我还必须提到这两个项目都是纯 .NET 5 库项目,并且在服务层项目中,我手动构建了 ServiceCollection:var services = new ServiceCollection();

我搜索了解决方案,但没有找到。

谢谢

我认为你不能向构造函数中注入任何东西。您应该使用 documentation:

中描述的方式
public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
    public BloggingContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
        optionsBuilder.UseSqlite("Data Source=blog.db");

        return new BloggingContext(optionsBuilder.Options);
    }
}

然后可以通过args传递任意参数:

dotnet ef database update -- --environment Production --connectionstring "some_connection_string"