C
C#5mo ago
hutoanhill

✅ Identity Services Registration not working

I declare a class to handle 'email':
public class MyEmailServices<TUser> : IEmailSender {
private readonly string _logFilePath = "fakeMail.txt";

public MyEmailServices() {

}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Format the log entry
string logEntry = $"[{DateTime.Now}] To: {email}\nSubject: {subject}\nMessage: {message}\n\n";

// Append the log entry to the file
await File.AppendAllTextAsync(_logFilePath, logEntry);
}
}
public class MyEmailServices<TUser> : IEmailSender {
private readonly string _logFilePath = "fakeMail.txt";

public MyEmailServices() {

}

public async Task SendEmailAsync(string email, string subject, string message)
{
// Format the log entry
string logEntry = $"[{DateTime.Now}] To: {email}\nSubject: {subject}\nMessage: {message}\n\n";

// Append the log entry to the file
await File.AppendAllTextAsync(_logFilePath, logEntry);
}
}
Then in Program.cs I register the service:
builder.Services.AddTransient<IEmailSender, MyEmailServices<IdentityUser>>();
builder.Services.AddTransient<IEmailSender, MyEmailServices<IdentityUser>>();
Finally i try and grab the service and it throws an error
var emailSender = endpoints.ServiceProvider.GetRequiredService<IEmailSender<TUser>>();
var emailSender = endpoints.ServiceProvider.GetRequiredService<IEmailSender<TUser>>();
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.IEmailSender`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.IEmailSender`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.
Everywhere i look it people use this same method to register the emailsender, so i am not sure what i am doing wrong.
7 Replies
Jimmacle
Jimmacle5mo ago
DI is trying to resolve a generic IEmailSender<IdentityUser> but you only show that you're registering a non-generic IEmailSender
hutoanhill
hutoanhillOP5mo ago
i get the same issues if i remove <TUser> from MyEmailService
Jimmacle
Jimmacle5mo ago
because that's not the problem you need to register the service as an IEmailSender<IdentityUser> not IEmailSender
hutoanhill
hutoanhillOP5mo ago
huh. ok. not sure what that wouldent be generic...
Jimmacle
Jimmacle5mo ago
because it's not, you used a different interface
hutoanhill
hutoanhillOP5mo ago
¯\_(ツ)_/¯ ok thanks hey its working! thanks a ton!
Jimmacle
Jimmacle5mo ago
:bless:
Want results from more Discord servers?
Add your server