一些服务无法构建。验证服务描述符时出错。

4
完整的错误信息
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负责用户创建(DB模型User),我需要调用SettingsService的AddSettings(DB模型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中,但我找不到任何相关信息。

2个回答

3
你应该注册 ISettingsService 服务:
services.AddTransient<ISettingsService, SettingsService>();

在您的示例中,您应该注册实现 ISettingsService 接口的类,就像实现 IUserRepository 接口的 UserRepository 类一样。

0

提示

在 Program.cs 或 StartUp.cs 中确认注册服务。
确认每个控制器中的构造函数注入或注入服务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接