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

问题描述 投票:-1回答:1

我已经阅读了很多关于stackoverflow的书籍和文章。仍然收到以下错误。这是我使用Generic Parameter的Interface,Repository的基本概要。我的Startup.cs中有AddTransient。

在控制器中,我试图引用接口,而不引用存储库名称。我有没有通用参数的东西。一旦我实现了通用参数,我就会收到以下错误。我想在不参考Repository或Model的情况下引用Interface,因为我们可能会在稍后从RelationalDB转到MongoDB等。如何摆脱这个错误?

接口:

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

库:

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

Startup.cs

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

控制器网页错误:

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

错误消息:错误CS0305使用泛型类型“IProductRepository”需要1个类型参数

c# asp.net-mvc asp.net-core dependency-injection repository
1个回答
0
投票

错误消息

错误消息告诉您确切的问题是什么。缺少类型参数。只需添加它:)此外,提供的错误代码CS0305是谷歌搜索/ binging的理想选择。

docs.microsoft.com说明如下:

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

可能的解决方案

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

1. Removing the generic parameter

如果您计划仅提供一种产品类型,则完全跳过通用参数,错误将消失。此外,您删除了不必要的复杂性。

Interace

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

Startup.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. Keeping the generic parameter

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

Startup.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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.