代码之家  ›  专栏  ›  技术社区  ›  Jeremy Thompson

无法为服务类型“IRepository”实例化实现类型存储库“1[TDBContext]”

  •  0
  • Jeremy Thompson  · 技术社区  · 2 年前

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

    程序反恐精英:

    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()
        {
        }
    }
    

    我尝试了一些建议,这些建议在这里显示为代码注释,但没有成功。有人能澄清一下我是如何连接存储库并在DbContext中加载DI的吗?

    1 回复  |  直到 2 年前
        1
  •  3
  •   Nkosi    2 年前

    检查存储库构造函数。容器不知道如何搬运 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>>();
    
    //...