Should I send e-mails in the service layer or in the controller layer?

Should I send e-mails in the service layer or in the controller layer?

你曾走过我的故事 发布于 2021-11-26 字数 719 浏览 903 回复 7 原文

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

柠檬 2022-06-07 7 楼

Actually I just have Controller Actions in my Controllers. All other business logic is taken care of by some other layer whatever that may be.

画尸师 2022-06-07 6 楼

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) :)

浅听莫相离 2022-06-07 5 楼

at mix and pdc phill said in his talk,

thin controllers, fat models
清浅ˋ旧时光 2022-06-07 4 楼

I would stick it in the service layer.

鲸落 2022-06-07 3 楼

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.

凹づ凸ル 2022-06-07 2 楼

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.

雪花飘飘的天空 2022-06-07 1 楼

Agreed. They belong in the service layer. The controller should only be very thin; just calling the appropriate business/data/whatever classes and dropping the data in the coinciding view.