Single Responsibility Principle in .NET Core
Are you tired of dealing with bloated and confusing code? The Single Responsibility Principle might just be the solution you need! This principle, which is the first in the solid design pattern, emphasizes that each class or module should have a single responsibility. Put simply, a class or module should only be responsible for one thing.
So, what exactly does responsibility mean in this context? It refers to the functionality of a class or module, such as adding, updating, deleting, or sending emails. Let’s take an employee class as an example — its responsibility might include Addemployee, UpdateEmployee, DeleteEmployee and SendingEmails.
In this article, we’ll explore the Single Responsibility Principle in more depth and discuss how you can implement it in your own code. Trust us, you won’t want to miss this one!
Let us Consider the following example
public class UserController : ControllerBase
{
private readonly ICommonRepository<User> _commonRepository;
public UserController(ICommonRepository<User> commonRepository)
{
_commonRepository = commonRepository;
}
public ActionResult<User> GetUser( Guid id)
{
var employee = _commonRepository.GetDetials(id);
return employee == null ? NotFound() : Ok(employee);
}
public ActionResult AddNewUser(User user)
{
_commonRepository.Insert(user);
var result=_commonRepository.SaveChanges();
if (result > 0)
{
return CreatedAtAction("GetUser", new { id = user.id }, user);
}
return BadRequest();
}
public void SendEmail(string toEmail, string subject)
{
SmtpClient client = new SmtpClient("smtp.ethereal.email", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("abby.wehner53@ethereal.email", "djgwPz8DPss78aakBv");
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("abby.wehner53@ethereal.email");
mailMessage.To.Add(toEmail);
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>User Registered</h1>");
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>Thank you For Registering account</p>");
mailMessage.Body = mailBody.ToString();
client.Send(mailMessage);
}
}
}
Take a look at the User controller — it’s responsible for getting user data, adding new users, and even sending emails. But wait a minute, does this class have a single responsibility? Not exactly — why are we sending emails in the User class?
And what if we need to send emails in other modules, such as with the Employee or Customer classes? Should we define a SendEmail method in each of those classes? It’s not the most efficient solution. Instead, we should create another class with the sole responsibility of sending emails. This way, the User class can focus solely on user-related responsibilities, the Employee class on employee-related responsibilities, and the Customer class on customer-related responsibilities.
To implement the Single Responsibility Principle in your code, it’s important to define clear interfaces and separate responsibilities. One way to do this is by creating an interface called IEmailSender and adding the SendEmail method to the interface:
namespace Sending_Emails_in_Asp.Net_Core
{
public interface IEmailSender
{
void SendEmail(string toEmail, string subject);
}
}
Next, we can create a class called EmailSender that inherits the IEmailSender interface and implements the SendEmail method as follows:
namespace Sending_Emails_in_Asp.Net_Core
{
public class EmailSender : IEmailSender
{
public void SendEmail(string toEmail, string subject)
{
// Set up SMTP client
SmtpClient client = new SmtpClient("smtp.ethereal.email", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("abby.wehner53@ethereal.email", "djgwPz8DPss78aakBv");
// Create email message
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("abby.wehner53@ethereal.email");
mailMessage.To.Add(toEmail);
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
StringBuilder mailBody = new StringBuilder();
mailBody.AppendFormat("<h1>User Registered</h1>");
mailBody.AppendFormat("<br />");
mailBody.AppendFormat("<p>Thank you For Registering account</p>");
mailMessage.Body = mailBody.ToString();
// Send email
client.Send(mailMessage);
}
}
}
By creating a separate class for sending emails, we can keep this responsibility separate from the User, Employee, and Customer classes. If we need to send emails in any of these classes, we can simply implement the IEmailSender interface and call the SendEmail method from the EmailSender class.
Implementing the Single Responsibility Principle in your code can lead to cleaner, more organized code that is easier to maintain and update over time.
To register the Email Service in Program.cs, you can use the following code:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEmailSender, EmailSender>();
This code sets up the dependency injection container to use EmailSender as the implementation of the IEmailSender interface.
Then, in your Controller, you can inject the IEmailSender dependency in the constructor and use it to send emails, like so:
public class UserController : ControllerBase
{
private readonly ICommonRepository<User> _commonRepository;
private readonly IEmailSender _emailSender;
public UserController(ICommonRepository<User> commonRepository, IEmailSender emailSender)
{
_commonRepository = commonRepository;
_emailSender = emailSender;
}
public ActionResult AddNewUser(User user)
{
_commonRepository.Insert(user);
var result=_commonRepository.SaveChanges();
_emailSender.SendEmail(user.Email, "User Regitered");
if (result > 0)
{
return CreatedAtAction("GetUser", new { id = user.id }, user);
}
return BadRequest();
}
}
By using dependency injection, you can easily swap out the implementation of IEmailSender with a different email service if needed.
Thank you for taking the time to read this article! I hope you found it informative and helpful. I value your opinion and would love to hear your feedback. Did you find the information helpful? Is there anything you would like me to elaborate on? Please share your thoughts and suggestions with me in the comments section below. Your feedback is important to me and will help me improve my content in the future.
Comments
Post a Comment