Reputation: 85
I am developping a web application using ASP.net core, I am new to this technology.
I am using a service to send emails, here is the class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Net.Mail;
namespace WebApplication.Services
{
public class MessageSender : IEmailSender, ISmsSender
{
public MessageSender(IOptions<MessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
public MessageSenderOptions Options { get; } //set only via Secret Manager
public Task SendEmailAsync(string email, string subject, string message)
{
// Plug in your email service here to send an email.
using (var smtp = new SmtpClient(Options.emailServer))
{
var mail = new MailMessage
{
Subject = subject,
IsBodyHtml = true,
From = new MailAddress(Options.fromEmail, Options.fromName),
Body = message
};
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development")
{
mail.To.Add(email);
}
else
{
mail.To.Add("[email protected]");
}
smtp.Send(mail);
}
return Task.FromResult(0);
}
public Task SendSmsAsync(string number, string message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
public class MessageSenderOptions
{
public List<string> emails { get; set; }
public string emailServer { get; set; }
public string fromEmail { get; set; }
public string fromName { get; set; }
}
}
And I am calling it in my controller this way :
namespace WebApplication.Controllers
{
[Route("api/[controller]")]
public class MyController : Controller
{
private readonly Context _Context;
private IHostingEnvironment _environment;
private ILogger<MyController> _logger;
private MessageSender _messageSender;
public MyController(IOptions<RegistrarConnection> optionsAccessor,
Context dbContextd,
IHostingEnvironment environment,
ILogger<GestionAteliersController> logger,
MessageSender messageSender,
)
{
Options = optionsAccessor.Value;
_Context = dbContextd;
_environment = environment;
_logger = logger;
_messageSender = messageSender;
}
[Route("[action]")]
public IActionResult save([FromBody] Obj obj)
{
try
{
//code
string subjet = "Subject";
string message = "Message";
_messageSender.SendEmailAsync("[email protected]", subjet, message);
var v = new { result = "OK" };
return this.Ok(v);
}
catch (Exception ex)
{
_logger.LogError(ex.ToString());
return new BadRequestObjectResult("Error");
}
}
It's just a part of the method, and everything works fine.
The problem that I have now is that I want to call this method
_messageSender.SendEmailAsync("[email protected]", subjet, message);
outside the controller, in another class and I don't know hot to use it as the controller do easily.
I don't understand how it's using the constructor of the class MessageSender.
In the Startup.cs file there is this part of code in the method ConfigureServices :
services.Configure<MessageSenderOptions>(Configuration.GetSection("MessageSenderOptions"));
services.AddTransient<IEmailSender, MessageSender>();
services.AddTransient<ISmsSender, MessageSender>();
services.AddTransient<MessageSender, MessageSender>();
And in my file appsettings.json there is this part of code :
"MessageSenderOptions": {
"emailServer": "smtp.gmail.ca",
"emails": [
"[email protected]"
],
"fromEmail": "[email protected]",
"fromName": "Test"
}
So I assume that in some way when the constructor of mycontroller is called, it's like if this line do all the job :
_messageSender = messageSender;
By calling the contructor of MessageSender and using the parameter IOptions < MessageSenderOptions > from the appsettings.json file.
But I don't know how to use that in another class:
public class HelloJob : IJob
{
/*private readonly ILogger _logger;
*/
private MessageSender _messageSender;
_messageSender.SendEmailAsync("[email protected]", subjet, message);
}
How can I instantiate the MessageSender using the parameters of appsettings.json used in Startup.cs to call the method SendEmailAsync
Thank you for your help
Upvotes: 0
Views: 386
Reputation: 840
Check this url https://learn.microsoft.com/fr-fr/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.0
You need pass an instance of your class in your constructor
public class HelloJob : IJob
{
private readonly MessageSender _messageSender;
public HelloJob(MessageSender messageSender)
{
_messageSender = messageSender;
}
}
Upvotes: 1