C
C#2mo ago
hutonahill

✅ 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
Jimmacle2mo ago
DI is trying to resolve a generic IEmailSender<IdentityUser> but you only show that you're registering a non-generic IEmailSender
hutonahill
hutonahill2mo ago
i get the same issues if i remove <TUser> from MyEmailService
Jimmacle
Jimmacle2mo ago
because that's not the problem you need to register the service as an IEmailSender<IdentityUser> not IEmailSender
hutonahill
hutonahill2mo ago
huh. ok. not sure what that wouldent be generic...
Jimmacle
Jimmacle2mo ago
because it's not, you used a different interface
hutonahill
hutonahill2mo ago
¯\_(ツ)_/¯ ok thanks hey its working! thanks a ton!
Jimmacle
Jimmacle2mo ago
:bless:
Want results from more Discord servers?
Add your server