I have not had much experience using Dependency Injection but I am trying to use it in one of my projects. When I try to add a second parameter to the constructor of my I get an error "Cannot consume scoped service 'CarbonService' from singleton..." Not sure why I get this error or what I am missing. Thanks for your help
I would like my timer class to have access to the CarbonService object.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<CarbonDBContext>(o => o.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddHostedService<ValidUntilTimerService>();
services.AddScoped<ICarbonService, CarbonService>(); // I HAVE TRIED USING SINGLETON BUT SAME ERROR
services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
}
ValidUntilTimerService.cs:
// ADDING THE SECOND PARAMETER TO THIS CONSTRUCTOR CAUSES THE ERROR.
public class ValidUntilTimerService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
private ICarbonService _carbonService;
public ValidUntilTimerService(ILogger<ValidUntilTimerService> logger, ICarbonService carbonService)
{
_logger = logger;
_carbonService = carbonService;
}
...
}
CarbonService.cs:
public interface ICarbonService
{
WattTime ReadCarbon();
void SaveCarbon(int carbonIndex);
}
public class CarbonService : ICarbonService
{
private IConfiguration _configuration;
private readonly CarbonDBContext _dbcontext;
public CarbonService(IConfiguration configuration, CarbonDBContext dbContext)
{
_configuration = configuration;
_dbcontext = dbContext;
}
public WattTime ReadCarbon()
{
var wt = new WattTime();
...
return wt;
}
public void SaveCarbon(int carbonIndex)
{
...
}
}