0

I'm having the following error, I can't start this class, I would like you to help me solve it please.

Error:

System.InvalidOperationException: Unable to resolve service for type 'IcarusOnlineAPI.Services.Email.SendEmail' while attempting to activate 'IcarusOnlineAPI.Controllers.Auth.AuthController'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method10(Closure , IServiceProvider , Object[] ) at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0(ControllerContext controllerContext) at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.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() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    -Constructor Class--
    private readonly ICARUS_Login_DatabaseContext _loginContext;
    private readonly ICARUS_User_DatabaseContext _userContext;
    private readonly ICARUS_Char_DatabaseContext _charContext;
    private readonly WEBContext _webcontext;
    private readonly ILogger<AuthController> _logger;
    private readonly SendEmail _sendEmail;

    public AuthController(ILogger<AuthController> logger, 
        ICARUS_Login_DatabaseContext loginContext,
        ICARUS_User_DatabaseContext userContext, 
        ICARUS_Char_DatabaseContext charContext, 
        WEBContext webcontext,
        SendEmail sendEmail
        )
    {
        _loginContext = loginContext;
        _userContext = userContext;
        _charContext = charContext;
        _webcontext = webcontext;
        _logger = logger;
        _sendEmail = sendEmail;
    }

-- Send Email Class-


   using IcarusOnlineAPI.MailSender;
   using Microsoft.AspNetCore.Hosting;
   using Microsoft.Extensions.Configuration;
   using System.IO;
   using System.Threading.Tasks;

namespace IcarusOnlineAPI.Services.Email
{
    public class SendEmail
    {
        private readonly IWebHostEnvironment _env;
        private readonly AadGraphApiDelegatedClient _aadGraphApiDelegatedClient;
        private readonly IConfiguration _configuration;

        public SendEmail(IWebHostEnvironment env,
            AadGraphApiDelegatedClient aadGraphApiDelegatedClient,
            IConfiguration configuration)
        {
            _env = env;
            _aadGraphApiDelegatedClient = aadGraphApiDelegatedClient;
            _configuration = configuration;
        }

        public async Task SendRecoverAccountEmail(string Login, string Email, string Token)
        {
            await Task.Delay(10000);

            var emailTemplate = File.ReadAllText
                (Path.Combine(_env.WebRootPath, "EmailTemplates/RecoverAccount.html"));

            var emailContent = emailTemplate
                .Replace("{Login}", Login)
                .Replace("{Link}", _configuration["Url"] + "/RecoverAccount/" + Token);

            var emailMessage = new EmailBuilder()
                .CreateHtmlEmail(Email, "Recuperar Conta", emailContent);

            await _aadGraphApiDelegatedClient.SendEmailAsync(emailMessage);
        }
    }
}
1
  • You need to register dependency for SendMail class Commented Oct 13, 2021 at 3:18

1 Answer 1

1

The error is self-explanatory. you have public AuthController(SendEmail sendEmail) and Dependency Injection doesn't know how to instantiate sendEmail. It's not a good practice to pass concrete (class) variable in Controller's DI. You want to do something like this:

public interface ISendEmail { ... }
public class SendEmail : ISendEmail { ... }

and in startup.cs have something like

services.AddScoped<ISendEmail, SendEmail>();

Then in controller you would have

private ISendEmail _sendEmail;
public AuthController(ISendEmail sendEmail) {
   _sendEmail = sendEmail;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.