Reputation: 1339
I'm trying to use SendGrid
for send email with my ASP.NET Core
application, so I configured it in the following way:
Inside the ConfigureServices
method I added a Singleton
and a configuration to access to SendGrid
API:
services.AddSingleton<IEmailSender, IEmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
the class AuthMessageSenderOptions
is part of the software configuration:
public class AuthMessageSenderOptions
{
public string SendGridUser { get; set; }
public string SendGridKey { get; set; }
}
this class manage the SendGrid
username and the secret key.
I created a service
class with implement the IEmailSender
interface, this is the implementation:
public class EmailSender : IEmailSender
{
public AuthMessageSenderOptions Options { get; }
public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
public Task SendEmailAsync(string email, string subject, string message)
{
return Execute(Options.SendGridKey, subject, message, email);
}
public Task Execute(string apiKey, string subject, string message, string email)
{
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("[email protected]", "Foo"),
Subject = subject,
PlainTextContent = message,
HtmlContent = message
};
msg.AddTo(new EmailAddress(email));
msg.TrackingSettings = new TrackingSettings
{
ClickTracking = new ClickTracking { Enable = false }
};
return client.SendEmailAsync(msg);
}
}
Then in my Account
controller (which is used for perform the registration and login), I injected the IEmailSender
service to the constructor:
public class AccountController : Controller
{
private readonly IEmailSender _emailSender;
public AccountController(IEmailSender emailSender)
{
_emailSender = emailSender;
}
when I start the application I get this error:
System.ArgumentException: 'Cannot instantiate implementation type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' for service type 'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender'.'
inside the Program
class, in particular on this line:
CreateWebHostBuilder(args).Build().Run();
this is the full Program
class:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
What I did wrong?
I'm learning ASP.NET Core
so, sorry if I did something stupid, I followed this doc to implement the SendGrid
logic.
Upvotes: 2
Views: 541
Reputation: 91805
services.AddSingleton<IEmailSender, IEmailSender>();
should specify the implementation in the second template argument:
services.AddSingleton<IEmailSender, EmailSender>();
Upvotes: 6