我是Asp .Net Core的新手,我使用它创建了App . 我在我的项目中使用通用存储库 . 但我有一个错误:
尝试激活“ECommerce.Repository.ProductRepository”时,无法解析“Microsoft.EntityFrameworkCore.DbContext”类型的服务 .
BaseRepository
protected DbContext _dbContext;
protected readonly DbSet<T> _dbSet;
public BaseRepository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<T>();
}
Repository
public partial class ProductRepository : BaseRepository<Product>, IProductRepository
{
public ProductRepository(DbContext dbContext) : base(dbContext) { }
}
Service
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;
}
}
Validation
public partial class ProductValidation : BaseValidation<Product>, IProductValidation
{
private readonly IProductRepository _productRepository;
public ProductValidation(IProductRepository productRepository) : base(productRepository)
{
}
}
Startup
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>();
}
Controller
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的项目中非常完美
2 回答
根据您对其他答案的评论:
如果您确定应用程序中只有 ONE
DbContext
,您可以这样做要么
如果你不希望
DbContext
和ECommerceDbContext
解析为两个不同的实例您需要注入实际的DbContext类,在本例中为
ECommerceDbContext
.所以将构造函数更改为: