运行此设置代码时遇到标题中的错误:
程序.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>>();
//...
我遇到了同样的问题,但错误的原因是我分别配置了接口和实现,然后再次对绑定配置进行了相同的操作。删除单独的配置解决了这个问题。