Question

I am integrating a mailing list into an existing CMS in asp.net MVC.

I need to send a confirmation email to the subscriber. Where should I send it from, the controller, Or the service layer?

Clarification: I would definitely create a separate service method called SendConfirmationEmail(). The question is who calls it the controller handling the registration form or the service that added the pending request to the DB?

Obviously I can send it from both but which is proper MVC?

Was it helpful?

Solution

I guess the standard approach is to have an email service that is injected into your controller and the controller only invokes the service operation like _emailService.Enqueue(myMessage).

public class MyController
{
    IEmailService _emailService;

    public MyController(IEmailService emailService)
    {
        _emailService = emailService;
    }

    public ActionResult Email()
    {
        var myMessage = new MyMessage();

        // Initialize message here

        _emailService.Enqueue(myMessage);
        return View();
    }
}

Some of the benefits are:

  • reuse : if you need to use the email functionality in another controller / action
  • testability : you can mock the email service in unit tests so your tests don't rely on an SMTP server
  • you can substitute mailing implementation and instead of sending mail directly queue it for async sending

OTHER TIPS

MVC encourages a separation of concerns so placement of behavior within the layers all about addressing the concern of the behavior. Since I am unfamiliar with your architecture I don't know what you mean by "service layer" but since sending emails has little to do with the models, views, or controllers of your website I would encourage you to move this functionality into an application layer where it belongs.

If your service layer is, in fact, and application layer then I would put the code there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top