【问题标题】:.Net 6 Unable to resolve service for type Microsoft.EntityFrameworkCore.DbSet.Net 6 无法解析 Microsoft.EntityFrameworkCore.DbSet 类型的服务
【发布时间】:2022-09-30 19:58:52
【问题描述】:

System.InvalidOperationException:无法解析类型 \'Microsoft.EntityFrameworkCore.DbSet1[Entities.Product]\' while attempting to activate \'Drin.Data.Repositories.GenericRepository1[Entities.Product]\' 的服务。

尝试执行控制器方法时出现此错误

  • 请分享代码,因为问题应该存在,而不是在招摇 ui 中。
  • 请不要将代码共享为图像,将其共享为文本。同样是上下文类,而不是导致问题的存储库之一。

标签: c# api dependency-injection .net-6.0 invalidoperationexception


【解决方案1】:

您似乎正在将DbSet<Product> 注入您的存储库。通常的方法是使用AddDbContextAddDbContextFactory 仅在DI 中注册上下文并在存储库中解析上下文:

public class SomeClassDependingOnDb
{
    public class SomeClassDependingOnDb(SomeAppDbContext context) => _context = context;
    ... 
}

然后,您可以使用它通过泛型类型通过Set<TEntity> 方法访问特定的DbSet - _context.Set<TEntity>(如果持有方法/类型是TEntity 的泛型)。

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 2022-01-10
    相关资源
    最近更新 更多