Should I send e-mails in the service layer or in the controller layer?
I am using the MVC pattern in ASP.NET using service (BLL) and repository layers for data managment. In some cases, I want to send out an automatic e-mail when a new request is sent through our website. In what layer of the architecture should this e-mail be sent? In the controller layer or the service layer? I was thinking the service layer, since that is where "business logic" is supposed to go, but am not 100% sure if that is semantically correct.
Edit: When I say "new request" I mean that a user takes an action that saves to some sort of datastore. As an example they create a new "Project" on the website. So the request will pass through the controller > service > repository layers.
如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

评论(7)


If it's a core business function I would put it in the service layer.
I might however abstract a "MailSender" class so that my service layer isn't explicitly tied to sending email in a particular way (e.g. using System.Web.Mail). You may want to use another method later on (e.g. sending mail asyncronously using queues). It also allows you to unit test safely without spamming anyone (by replacing MailSender with one that doesn't actually send any mail) :)

I always design my business layer so that it's capable of working regardless of the medium through which the data is presented. So, for example, if I were to send an email when a new account is created, I would like this to occur regardless of whether the user is creating the account via a website or a desktop application. In that case, the sending of the email would occur in the business layer because it is common to both mediums.

Most of the time you can clarify issues like this by thinking about what you would want to happen if you had a web service layer or a windows app in front of your BLL instead of your web app. Would you still want the same email to go out? If the answer is yes, then sending the email is part of your business model and it should go in the BLL. if the answer is no, then sending the email is really application logic and it should go in your app layer.
发布评论
需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。