【问题标题】:Error when trying to add Irepositories to services with addScoped ASP.Net core 2.1尝试使用 addScoped ASP.Net core 2.1 将 Irepositories 添加到服务时出错
【发布时间】:2018-09-13 10:56:09
【问题描述】:

我正在尝试将我的 Irepository 接口和 irepository 添加到服务中,以便我可以使用它们。

我是这样做的:

services.AddScoped<AuctioniRepository, IrepoAuctionInterface>();

这是我得到的错误:

错误 CS0311 类型“NackowskiLillMygel.Data.IrepoAuctionInterface”不能用作泛型类型或方法“ServiceCollectionServiceExtensions.AddScoped(IServiceCollection)”中的类型参数“TImplementation”。没有从“NackowskiLillMygel.Data.IrepoAuctionInterface”到“NackowskiLillMygel.Data.AuctioniRepository”的隐式引用转换。 NackowskiLillMygel 源\repos\NackowskiLillMygel\NackowskiLillMygel\Startup.cs 39 活动

我不明白我做错了什么。 另外,如果您需要来自存储库的更多代码,请告诉我。

非常感谢您的回答!

【问题讨论】:

  • 添加服务的正确方法是先InterfaceClass。所以应该是services.AddScoped&lt;IrepoAuctionInterface, AuctioniRepository&gt;();

标签: c# asp.net asp.net-core


【解决方案1】:

您正在将接口注册为IrepoAuctionInterface 的实现。 .AddScoped() 方法的签名如下:

public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services)
    where TService : class
    where TImplementation : class, TService;

这意味着TService 应该实现TImplementation,而你却反过来了。

你应该像这样翻转参数:

services.AddScoped<IrepoAuctionInterface, AuctioniRepository>();

【讨论】:

  • 哇,哈哈。多谢,伙计!还有一个问题,如果我也想实现另一个 Irepo,我是否只需编写另一个 AddScoped?
  • 一般情况下是可以的,但是你会在 DI 容器中消费最后注册的IrepoAuctionInterface(所以顺序很重要)。如果你想消费所有注册的服务,你应该消费IEnumerable&lt;IrepoAuctionInterface
  • 如果您需要通过 DI 容器从相同接口类型的多个存储库访问特定存储库,您要么必须注入所需的具体类型,要么需要实现一个工厂并注入它。工厂模式通常更适合。
【解决方案2】:

只需在AuctioniRepository类中实现接口IrepoAuctionInterface

喜欢

public class AuctioniRepository : IrepoAuctionInterface
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2016-12-18
    • 2021-08-28
    • 2011-04-15
    • 1970-01-01
    • 2020-02-20
    相关资源
    最近更新 更多