首页 > 解决方案 > 添加依赖注入会在 .NET Core 中产生异常

问题描述

我收到以下异常。为什么会这样,我该如何解决?

SMSService.cs我评论构造函数时,它开始工作,但我需要ISMSSender从它访问。

System.AggregateException:'某些服务无法构造(验证服务描述符时出错'ServiceType:Authentication.API.Repository.Interface.ISMSService Lifetime:Singleton ImplementationType:Authentication.API.Repository.SMSService':无法解析服务尝试激活“Authentication.API.Repository.SMSService”时输入“SMSSender.API.Repository.Interface.ISMSSender”。)

Authentication.API.Repository.SMSService

public class SMSService : ISMSService
{
    private readonly ISMSSender _smsSender;

    public SMSService(ISMSSender smsSender)
    {
        _smsSender = smsSender;
    }
}

启动 ...

         services.AddTransient<ISMSService, SMSService>();

         ...

SMSSender.API.Repository.Interface.ISMSSender

public interface ISMSSender
{
    Task<SMSUser> SendSMS(SMSUser prospectiveUser);
}

SMSSender.API.Repository.Interface.SMSSender

public class SMSSender : ISMSSender
{
    public async Task<SMSUser> SendSMS(SMSUser sMSUser)
    { }

}

标签: c#.net-coredependency-injection

解决方案


看起来你没有注册 SMSSender(你做了服务):

services.AddTransient<ISMSService, SMSService>();
services.AddTransient<ISMSSender, SMSSender>();

推荐阅读