builder.Services.AddDbContext(opt => opt.UseInMemoryDatabase("My"));
// Can't work out how to wire up the Repository?
//builder.Services.AddScoped(p => new TDBContext());
//builder.Services.AddScoped();
builder.Services.AddScoped(typeof(IRepository), typeof(Repository));
//builder.Services.AddScoped(typeof(IRepository), typeof(Repository));
builder.Services.AddScoped();
var app = builder.Build(); //ERROR HERE!
public class MyService : IMyService
{
private readonly IRepository _repository;
public MyService(IRepository repository)
{
_repository = repository;
}
}
public class Repository : IRepository where TDBContext : DbContext
{
protected DbContext dbContext;
public Repository(DbContext context)
{
dbContext = context;
}
public async Task CreateAsync(T entity) where T : class
{
this.dbContext.Set().Add(entity);
return await this.dbContext.SaveChangesAsync();
}
//.....
}
public class TDBContext : DbContext
{
public TDBContext(DbContextOptions options)
: base(options)
{
}
public virtual DbSet Transactions { get; set; } = null!;
public TDBContext()
{
}
}
Я попробовал несколько предложений, представленных здесь в виде комментариев к коду, но безуспешно. Может ли кто-нибудь объяснить, как мне подключить репозиторий и загрузить DI в DbContext?
Я вижу ошибку в заголовке при запуске этого кода установки: Program.cs: [code]builder.Services.AddDbContext(opt => opt.UseInMemoryDatabase("My"));
// Can't work out how to wire up the Repository? //builder.Services.AddScoped(p => new TDBContext()); //builder.Services.AddScoped(); builder.Services.AddScoped(typeof(IRepository), typeof(Repository)); //builder.Services.AddScoped(typeof(IRepository), typeof(Repository));
builder.Services.AddScoped();
var app = builder.Build(); //ERROR HERE! [/code] Сервис и репозиторий: [code]public class MyService : IMyService { private readonly IRepository _repository;
public MyService(IRepository repository) { _repository = repository; } }
public class Repository : IRepository where TDBContext : DbContext { protected DbContext dbContext;
public Repository(DbContext context) { dbContext = context; } public async Task CreateAsync(T entity) where T : class { this.dbContext.Set().Add(entity); return await this.dbContext.SaveChangesAsync(); } //..... }
public class TDBContext : DbContext { public TDBContext(DbContextOptions options) : base(options) { }
public virtual DbSet Transactions { get; set; } = null!;
public TDBContext() { } } [/code] Я попробовал несколько предложений, представленных здесь в виде комментариев к коду, но безуспешно. Может ли кто-нибудь объяснить, как мне подключить репозиторий и загрузить DI в DbContext?