-
Notifications
You must be signed in to change notification settings - Fork 1
Using an IOC Container Ninject
Creating a RazorMailSender every time you need to send email goes against the DRY principle. It also makes it extremely difficult to manually test emailing across your application, alter network credentials or alter sender details.
By initialising the RazorMailSender via an IOC container you can easily reconfigure mail delivery throughout your application, creating a single point of change.
The example below demonstrates a Ninject implementation within an ASP.NET MVC application.
Lets imagine our domain object sends an email on confirmation.
public class Booking
{
public string BookingCode { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public bool Confirmed { get; set; }
public void Confirm(IRazorMailSender sender)
{
var message = new RazorMailMessage("Booking Confirmation");
message.To.Add(Email, Name);
message.From = new MailAddress("bookings@domain.com", "Business Name Booking Department");
message.Templates.Add("Thank you @Model.Name for your booking. Your booking code is @Model.BookingCode.");
message.Set.Name = Name;
message.Set.BookingCode = BookingCode;
sender.Send(message);
Confirmed = true;
}
}We can define an IRazorMailSender within out IOC container to be passed around the application on a per request basis whenever it is required.
kernel
.Bind<IRazorMailSender>()
.To<RazorMailSender>()
.InRequestScope()
.WithConstructorArgument("sender", new MailAddress("no-reply@domain.com", "Business Name"))
.WithConstructorArgument("baseUri", x => HttpContext.Current.Request.Url)
.WithConstructorArgument("client", new SmtpClient("127.0.0.1") { Credentials = new NetworkCredential("username", "password") });We simply inject our IRazorMailSender into our controller. It can then be passed to the domain object when confirming the booking.
public class BookingController : Controller
{
IRazorMailSender _sender;
IBookingRepository _bookingRepository;
public BookingController(IRazorMailSender sender, IBookingRepository bookingRepository)
{
_sender = sender;
_bookingRepository = bookingRepository;
}
public ActionResult Confirm(Guid id)
{
var booking = _bookingRepository.GetById(id);
booking.Confirm(_sender);
return RedirectToAction("Index");
}
}