0

This is my program.cs

using TestEmailTaskScheduler.Controllers;
using TestEmailTaskScheduler.Models;
using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSingleton<EmailService>();
builder.Services.AddHostedService<EmailService>();
builder.Configuration.GetSection("DailyEmail").Get<MySettingsModel>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

And this is a part of the test code in my controller service:

using Microsoft.Extensions.Options;
using TestEmailTaskScheduler.Models;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Configuration;

namespace TestEmailTaskScheduler.Controllers
{
    public class EmailService : BackgroundService
    {
        private const int generalDelay = 1 * 10 * 1000; // 10 seconds
        private readonly IOptions<MySettingsModel> appSettings;
        private readonly IOptions<MyDatabaseModel> databaseSettings;
        private Timer Schedular;

    public EmailService(IOptions<MySettingsModel> app)
    {
        appSettings = app;
    }
    public EmailService(IOptions<MyDatabaseModel> dbs)
    {
        databaseSettings = dbs!;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(generalDelay, stoppingToken);
            await DoBackupAsync();
        }
    }

    private Task DoBackupAsync()
    {
        // here i can write logic for taking backup at midnight
        if (IsMidnight())
        {
            Console.WriteLine("Executing background task");
            //SendEmail();
        }

        return Task.FromResult("Done");
    }

Error: System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: TestEmailTaskScheduler.Controllers.EmailService Lifetime: Singleton ImplementationType: TestEmailTaskScheduler.Controllers.EmailService': Unable to activate type 'TestEmailTaskScheduler.Controllers.EmailService'. The following constructors are ambiguous: Void .ctor(Microsoft.Extensions.Options.IOptions1[TestEmailTaskScheduler.Models.MySettingsModel]) Void .ctor(Microsoft.Extensions.Options.IOptions1[TestEmailTaskScheduler.Models.MyDatabaseModel])) (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: TestEmailTaskScheduler.Controllers.EmailService': Unable to activate type 'TestEmailTaskScheduler.Controllers.EmailService'. The following constructors are ambiguous: Void .ctor(Microsoft.Extensions.Options.IOptions1[TestEmailTaskScheduler.Models.MySettingsModel]) Void .ctor(Microsoft.Extensions.Options.IOptions1[TestEmailTaskScheduler.Models.MyDatabaseModel]))'

Why is this happening? I thought it is already called in the program.cs?

6
  • 3
    For DI to work properly, you need to have exactly one constructor. eg EmailService(IOptions<MySettingsModel> app, IOptions<MyDatabaseModel> dbs){...} Commented Oct 4, 2022 at 3:22
  • Check your appsettings.json. It is likely that it does not have the section named "DailyEmail". You are also using the contructor incorrectly. Simply use MyDatabaseModel (instead of IOptions<MyDatabaseModel> ) if you are directly using Get<T> on options config. Commented Oct 4, 2022 at 4:28
  • I followed what @JeremyLakeman and it started running, but now the error is that the appsetting value is null, although it is taking it from the appsettings.json 'DailyEmail'. the DailyEmail is there, but I dont know why the value is null Commented Oct 4, 2022 at 4:54
  • .GetSection("DailyEmail").Get<MySettingsModel>() will return the config object. What you want is .Configure<MySettingsModel>(....GetSection("DailyEmail")) which you should see in other examples / tutorials. Commented Oct 4, 2022 at 5:05
  • @JeremyLakeman I did this code before "builder.Services.Configure<MySettingsModel>(Configuration.GetSection("DailyEmail"));" but i get this error cs0120: An object reference is required for the nonstatic field, method, or property 'member' for the 'Configuration.GetSection' part Commented Oct 4, 2022 at 5:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.