无法实例化服务类型 'IRepository' 的实现类型 Repository`1[TDBContext]'。

Cannot instantiate implementation type Repository`1[TDBContext]' for service type 'IRepository'.'

当 运行 此设置代码时,我遇到了标题中的错误:

Program.cs:

builder.Services.AddDbContext<TDBContext>(opt => opt.UseInMemoryDatabase("My"));

// Can't work out how to wire up the Repository?
//builder.Services.AddScoped<IRepository>(p => new TDBContext());
//builder.Services.AddScoped<IRepository, Repository>();
builder.Services.AddScoped(typeof(IRepository), typeof(Repository<>));
//builder.Services.AddScoped(typeof(IRepository), typeof(Repository<TDBContext>));

builder.Services.AddScoped<IMyService, MyService>();

var app = builder.Build();  //ERROR HERE!

服务和存储库:

public class MyService : IMyService
{
    private readonly IRepository _repository;
    
    public MyService(IRepository repository)
    {          
        _repository = repository;
    }
}
    
public class Repository<TDBContext> : IRepository where TDBContext : DbContext
{
    protected DbContext dbContext;

    public Repository(DbContext context)
    {
        dbContext = context;
    }
    public async Task<int> CreateAsync<T>(T entity) where T : class
    {
        this.dbContext.Set<T>().Add(entity);
        return await this.dbContext.SaveChangesAsync();
    }
    //.....
}


public class TDBContext : DbContext
{
    public TDBContext(DbContextOptions<TDBContext> options)
        : base(options)
    {
    }

    public virtual DbSet<MyTransaction> Transactions { get; set; } = null!;

    public TDBContext()
    {
    }
}

我已经尝试了一些在此处显示为代码注释的建议,但没有成功。有人可以阐明我如何连接存储库并让 DI 加载到 DbContext 中吗?

检查存储库构造函数。容器在解析存储库时不知道如何将 DbContext 作为依赖项处理。

您是想改用泛型参数类型吗?

此外,通用参数的命名可能会造成混淆。

public class Repository<TContext> : IRepository where TContext : DbContext {
    protected DbContext dbContext;

    public Repository(TContext context) {
        dbContext = context;
    }

    public async Task<int> CreateAsync<T>(T entity) where T : class {
        this.dbContext.Set<T>().Add(entity);
        return await this.dbContext.SaveChangesAsync();
    }

    //.....
}

并且注册需要使用封闭式

//...

builder.Services.AddScoped<IRepository, Repository<TDBContext>>();

//...