我是Asp .Net Core的新手,我使用它创建了App。我在我的项目中使用通用存储库。但我有一个错误:
无法解析类型' Microsoft.EntityFrameworkCore.DbContext'在尝试激活' ECommerce.Repository.ProductRepository'。
时
BaseRepository
protected DbContext _dbContext;
protected readonly DbSet<T> _dbSet;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<T>();
}
存储库
public partial class ProductRepository : BaseRepository<Product>, IProductRepository
{
public ProductRepository(DbContext dbContext) : base(dbContext) { }
}
服务
public partial class ProductService : BaseService<Product>, IProductService
{
private readonly IProductRepository _repository;
private readonly IProductValidation _validation;
private readonly IUnitOfWork _unitOfWork;
public ProductService(IProductValidation validation, IProductRepository respository, IUnitOfWork unitOfWork)
: base(validation, respository, unitOfWork)
{
_repository = respository;
_validation = validation;
_unitOfWork = unitOfWork;
}
}
验证
public partial class ProductValidation : BaseValidation<Product>, IProductValidation
{
private readonly IProductRepository _productRepository;
public ProductValidation(IProductRepository productRepository) : base(productRepository)
{
}
}
启动
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ECommerceDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Add framework services.
services.AddMvc();
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddTransient<IProductRepository, ProductRepository>();
services.AddTransient<IProductService, ProductService>();
services.AddTransient<IProductValidation, ProductValidation>();
}
控制器
private readonly IProductService _productService;
public ValuesController(IProductService productService)
{
_productService = productService;
}
// GET api/values
[HttpGet]
public IEnumerable<Product> Get()
{
return _productService.GetAll();
}
请告诉我我的代码有什么问题。非常感谢
P / s:此代码在我之前使用Autofac
使用Asp .Net 4.6的项目中非常完美答案 0 :(得分:2)
根据您对其他答案的评论:
如果您确定应用中只有 ONE DbContext
,则可以
services.AddScoped<DbContext, ECommerceDbContext>();
或
services.AddScoped<DbContext>(provider => provider.GetRequiredService<ECommerceDbContext>());
如果您不希望DbContext
和ECommerceDbContext
解析为两个不同的实例
答案 1 :(得分:0)
您需要注入实际的DbContext类,在本例中为ECommerceDbContext
。
所以将构造函数更改为:
public BaseRepository(ECommerceDbContext dbContext)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<T>();
}