【问题标题】:Some services are not able to be constructed. Error while validating the service descriptor某些服务无法构建。验证服务描述符时出错
【发布时间】:2021-11-10 21:11:46
【问题描述】:

完整的错误正文

System.AggregateException: 'Some services are not able to be constructed 
(Error while validating the service descriptor 'ServiceType: WebApp.Application.Common.Interfaces.IUserService
Lifetime: Transient ImplementationType: WebApp.Application.Common.Services.UserService':
Unable to resolve service for type 'WebApp.Application.Common.Interfaces.ISettingsService'
while attempting to activate 'WebApp.Application.Common.Services.UserService'.)'

我让 UserService 负责创建用户(数据库模型用户),我需要从 SettingsService 调用 AddSettings(数据库模型 NotificationSettings、PersonalSettings)来为新注册的用户创建设置对象。目前,我正在尝试通过 UserService 的 AddUser 方法来实现:

public void AddUser(AddUserDTO addUserDTO)
{
   try
   {
        userRepository.AddAsync(mapper.Map<AddUserDTO, User>(addUserDTO));
        var user = userRepository.FindAsync(a => a.FullName == addUserDTO.FullName && a.Email == addUserDTO.Email);
        settingsService.AddSettings(user.Id);
   }
   catch (Exception ex)
   {
       logger.LogError(ex.Message);
       throw;
   }
}

AddSettings 方法:

public async void AddSettings(int id)
{
    try
    {
        notificationSettingsRepository.Add(new NotificationSettings
        {
            UserId = id,
            PushNewFollowerNotify = false,
            PushNewMessageNotify = false,
            PushLikeNotify = false
        });
        personalSettingsRepository.Add(new PersonalSettings
        {
            UserId = id,
            FollowerSeeFollowers = false,
            FollowerSeeSavedRecipe = false,
        });
    }
    catch (Exception ex)
    {
        logger.LogError(ex.Message);
    }
}

UserService 构造函数:

private readonly IUserRepository userRepository;
private readonly ISettingsService settingsService;
private readonly ILogger<UserService> logger;
private readonly IMapper mapper;

public UserService(IUserRepository userRepository, ISettingsService settingsService, ILogger<UserService> logger, IMapper mapper)
{
    this.userRepository = userRepository;
    this.settingsService = settingsService;
    this.logger = logger;
    this.mapper = mapper;
}

并且这两个服务都在 Startup.cs 中注册

services.AddTransient<ISearchService, SearchService>();
services.AddTransient<IUserService, UserService>();

我认为问题在于我如何将 SettingsService 注入 UserService,但我找不到任何相关信息。

【问题讨论】:

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


    【解决方案1】:

    你应该注册ISettingsService服务:

    services.AddTransient<ISettingsService, SettingsService>();
    

    在您的示例中,您应该注册一个实现ISettingsService 接口的类,例如实现IUserRepository 接口的UserRepository

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 2021-07-09
      • 1970-01-01
      • 2023-02-03
      • 2020-06-04
      • 2023-03-08
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多