MVC 核心依赖项注入:接口存储库通用参数错误



我已经阅读了许多关于stackoverflow的书籍和文章。 仍然收到以下错误。这是我对接口的基本概述,带有通用参数的存储库。我的Startup.cs中有AddTransient 。

在控制器中,我尝试引用接口,而不引用存储库名称。我有没有通用参数的东西工作。一旦我实现了通用参数,我就会收到下面的错误。我想引用接口而不引用存储库或模型,因为我们稍后可能会从 RelationalDB 转到 MongoDB,等等。如何摆脱此错误?

接口:

public interface IProductRepository<T>: IDisposable where T:class
{
IEnumerable<T> GetProductDetail();

存储 库:

public class ProductRepository: IProductRepository<ProductdbData>
{
IEnumerable<ProductdbData> GetProductDetail(); 

启动.cs

services.AddTransient(typeof(IProductRepository<>), typeof(ProductRepository));

控制器网页错误:

namespace CompanyWeb.Controllers
{
public class ProductController: Controller
{
private IProductRepository _productwebrepository; // this line gives error

错误信息: 错误 CS0305 使用泛型类型"IProduct存储库"需要 1 个类型参数

错误消息

错误消息准确地告诉您问题所在。缺少类型参数。只需将其添加到:) 此外,提供的错误代码CS0305是谷歌搜索/狂欢的完美候选者。

learn.microsoft.com 声明如下:

当找不到预期数量的类型参数时,会发生此错误。若要解析 C0305,请使用所需数量的类型参数。

可能的解决方案

有多种方法可以解决问题。

1. 删除泛型参数

如果您打算只提供一种产品类型,请完全跳过通用参数,错误将消失。此外,您还可以消除不必要的复杂性。

英特斯

public interface IProductRepository: IDisposable
{
IEnumerable<ProductdbData> GetProductDetail();

启动.cs

services.AddTransient<IProductRepository, ProductRepository>();

控制器:

namespace CompanyWeb.Controllers
{
[Route("api/[controller]")]
public class ProductController : Controller
{
private IProductRepository _ProductRepository;
public ProductController(IProductRepository productRepository)
{
_ProductRepository = productRepository;
}

2. 保留泛型参数

如果您决定坚持使用泛型参数,则实际上必须修复控制器和接口,并在两个位置传递泛型类型参数。

启动.cs

services.AddTransient<IProductRepository<ProductdbData>, ProductRepository>();

控制器:

namespace CompanyWeb.Controllers
{
[Route("api/[controller]")]
public class ProductController : Controller
{
private IProductRepository<ProductdbData> _ProductRepository;
public ProductController(IProductRepository<ProductdbData> productRepository)
{
_ProductRepository = productRepository;
}

最新更新