Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered
System.InvalidOperationException: Unable to resolve service for type 'BotLab.me.Services.StatisticBackgroundService' while attempting to activate 'BotLab.Net.Controllers.StatsController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type type, Type requiredBy)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean hasDefaultValue, Object key)
at lambda_method340(Closure, IServiceProvider, Object[])
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
ошибка когда обращаюсь к контроллеру
[Route("api/[controller]")]
[ApiController]
public class StatsController : ControllerBase
{
private readonly IStatisticRepository _statisticRepository;
private readonly StatisticBackgroundService _statisticBackgroundService;
public StatsController(IStatisticRepository statisticRepository, StatisticBackgroundService statisticBackgroundService)
{
_statisticRepository = statisticRepository;
_statisticBackgroundService = statisticBackgroundService;
}
// POST api/<StatsController>
[HttpPost]
public ActionResult Post([FromBody] List<Statistic> value, [FromQuery] string key)
{
if (value != null && !string.IsNullOrEmpty(key) && key == "HelloWorld!!!12345")
{
_statisticRepository.Add(value);
foreach (var item in value)
{
_statisticBackgroundService.AddStaticBd(item);
}
return Ok();
}
return BadRequest();
}
}
вот Background сервис:
public class StatisticBackgroundService : BackgroundService
{
private readonly ILogger<StatisticBackgroundService> _logger;
private readonly IStatisticRepository _statisticRepository;
private readonly IServiceProvider _serviceProvider;
public StatisticBackgroundService(
ILogger<StatisticBackgroundService> logger,
IStatisticRepository statisticRepository,
IServiceProvider serviceProvider)
{
_logger = logger;
_statisticRepository = statisticRepository;
_serviceProvider = serviceProvider;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var stats = _statisticRepository.Get();
if (stats.Count == 0)
{
await Task.Delay(1);
continue;
}
foreach ( var statistic in stats)
{
await AddStaticBd(statistic);
}
}
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Queued Hosted Service is stopping.");
await base.StopAsync(stoppingToken);
}
public async Task AddStaticBd(Statistic statisticDTO)
{
try
{
using var scope = _serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var st = await db.KeyStat.OrderByDescending(x => x.Created)
.FirstOrDefaultAsync(x =>
x.Key == statisticDTO.ApiKey
&& x.Ip == statisticDTO.Ip
&& x.SoftId == statisticDTO.SoftId);
if (st == null)
{
await db.KeyStat.AddAsync(new KeyStat
{
Bad= statisticDTO.Bad,
Good= statisticDTO.Good,
Ip= statisticDTO.Ip,
Key=statisticDTO.ApiKey,
SoftId= statisticDTO.SoftId
});
}
else
{
if(st.Created < DateTime.UtcNow.AddMinutes(3))
{
await db.KeyStat.AddAsync(new KeyStat
{
Bad = statisticDTO.Bad,
Good = statisticDTO.Good,
Ip = statisticDTO.Ip,
Key = statisticDTO.ApiKey,
SoftId = statisticDTO.SoftId
});
}
else
{
st.Good += statisticDTO.Good;
st.Bad += statisticDTO.Bad;
}
}
await db.SaveChangesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "AddStaticBd: {ex}", ex.Message);
_statisticRepository.Add(new List<Statistic> { statisticDTO });
}
}
}
как регистрирую:
builder.Services.AddHostedService<StatisticBackgroundService>();
мне нужно что бы BackgroundServices сохранял каждый обьект statistic в бд