我试图以以下方式使用依赖项注入,但是我的错误程度低于
InvalidOperationException:在试图激活“”时无法解析“”类型的服务。
我试图实现的是,我在通用接口中定义了一些常用方法,以及在存储库特定接口(如ICustomerRepository )中写入数据驱动逻辑的其他方法。
从控制器中,应该调用这些常见和具体的方法。但是,如前所述,在尝试执行API时,我会得到上述错误。
我之所以保留泛型存储库,因为在每个存储库添加时,不应该在StartUp.cs中添加这些存储库。
那么,如何通过存储库特定的接口来执行泛型和非泛型方法呢?
对此有任何帮助,非常感谢!
下面是我的代码
IGenericRepository.cs
public interface IGenericRepository<TEntity> where TEntity : class
{
IEnumerable<TEntity> GetAll();
TEntity GetById(int id);
void Create(TEntity entity);
Task Update(int id, TEntity entity);
TEntity Delete(int id);
}GenericRepository.cs
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
private readonly DbContext dbContext;
public GenericRepository(DbContext dbContext)
{
this.dbContext = dbContext;
}
public void Create(TEntity entity)
{
dbContext.Set<TEntity>().Add(entity);
dbContext.SaveChanges();
}
public TEntity Delete(int id)
{
throw new NotImplementedException();
}
public IEnumerable<TEntity> GetAll()
{
return dbContext.Set<TEntity>().ToList();
}
public TEntity GetById(int id)
{
return dbContext.Set<TEntity>().Find(id);
}
public Task Update(int id, TEntity entity)
{
throw new NotImplementedException();
}
IEnumerable<TEntity> IGenericRepository<TEntity>.GetAll()
{
return dbContext.Set<TEntity>().ToList();
}
}ICustomerRepository.cs
public interface ICustomerRepository : IGenericRepository<Customer>
{
Task<Customer> GetCustomerDetails();
}CustomerRepository.cs
public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository
{
private readonly BaseDBContext _dbContext;
public CustomerRepository(BaseDBContext dbContext)
: base(dbContext)
{
_dbContext = dbContext;
}
public Task<Customer> GetCustomerDetails()
{
throw new NotImplementedException();
}
}Customer.cs
public class Customer
{
[Key]
public int CustId { get; set; }
public string CustomerName { get; set; }
public string City { get; set; }
public string Designation { get; set; }
}StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer().AddDbContext<BaseDBContext>();
services.Configure<DBConfiguration>(Configuration.GetSection("DBConfiguration"));
services.AddScoped<DbContext, BaseDBContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));
}CustomerController.cs
private readonly ICustomerRepository custRepository;
public ValuesController(IOptions<DBConfiguration> dBConfiguration, ICustomerRepository _custRepository)
{
custRepository= _custRepository;
}发布于 2019-07-18 15:26:25
将此添加到StartUp.cs中
services.AddScoped<ICustomerRepository, CustomerRepository>();https://stackoverflow.com/questions/57097893
复制相似问题