Dependency Injection (DI) is a core feature in .NET Core that helps manage dependencies and promotes loose coupling in applications. In this guide, we’ll explore advanced DI concepts such as custom service lifetimes, scopes, and handling complex dependency graphs through a practical example: an e-commerce application.
Scenario. E-Commerce Application
In our e-commerce application, we have several services.
- Order Service: Manages customer orders.
- Payment Service: Handles payment processing.
- Notification Service: Sends notifications via email or SMS.
- Audit Service: Logs operations for auditing.
We'll ensure that these services are efficiently managed and injected into various parts of the application using DI.
Project Structure
- Interfaces: Define the contracts for our services.
- Implementations: Implement the service logic.
- Controllers: Use services to handle HTTP requests.
- Models: Define the data structures used in services.
Step-by-step implementation
1. Define Interfaces
Create interfaces for the services in the Interfaces folder.
Interfaces/Services/Interfaces.cs
public interface IOrderService
{
void PlaceOrder(Order order);
}
public interface IPaymentService
{
void ProcessPayment(Payment payment);
}
public interface INotificationService
{
void Notify(Notification notification);
}
public interface IAuditService
{
void LogOperation(string message);
}
2. Implement Services
Create concrete implementations for each service.
Services/OrderService.cs
public class OrderService : IOrderService
{
private readonly IPaymentService _paymentService;
private readonly INotificationService _notificationService;
private readonly IAuditService _auditService;
public OrderService(IPaymentService paymentService, INotificationService notificationService, IAuditService auditService)
{
_paymentService = paymentService;
_notificationService = notificationService;
_auditService = auditService;
}
public void PlaceOrder(Order order)
{
// Process payment
_paymentService.ProcessPayment(order.Payment);
// Notify customer
_notificationService.Notify(order.Notification);
// Log operation
_auditService.LogOperation($"Order placed for {order.Id}");
}
}
Services/PaymentService.cs
public class PaymentService : IPaymentService
{
private readonly IPaymentGatewayClient _paymentGatewayClient;
public PaymentService(IPaymentGatewayClient paymentGatewayClient)
{
_paymentGatewayClient = paymentGatewayClient;
}
public void ProcessPayment(Payment payment)
{
_paymentGatewayClient.MakePayment(payment);
}
}
Services/NotificationService.cs
using System.Net;
using System.Net.Mail;
public class NotificationService : INotificationService
{
private readonly SmtpClient _smtpClient;
private readonly ISmsClient _smsClient; // Hypothetical SMS client interface
public NotificationService(SmtpClient smtpClient, ISmsClient smsClient)
{
_smtpClient = smtpClient;
_smsClient = smsClient;
}
public void Notify(Notification notification)
{
switch (notification.Type)
{
case NotificationType.Email:
SendEmail(notification);
break;
case NotificationType.Sms:
SendSms(notification);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void SendEmail(Notification notification)
{
var mailMessage = new MailMessage
{
From = new MailAddress("[email protected]"),
Subject = "Notification",
Body = notification.Message,
IsBodyHtml = true
};
mailMessage.To.Add(notification.Recipient);
try
{
_smtpClient.Send(mailMessage);
}
catch (Exception ex)
{
// Handle exceptions (e.g., log errors)
Console.WriteLine($"Failed to send email: {ex.Message}");
}
}
private void SendSms(Notification notification)
{
try
{
// Assuming _smsClient.SendSms is a method to send SMS via a service
_smsClient.SendSms(notification.Recipient, notification.Message);
}
catch (Exception ex)
{
// Handle exceptions (e.g., log errors)
Console.WriteLine($"Failed to send SMS: {ex.Message}");
}
}
}
Services/AuditService.cs
using Microsoft.Extensions.Logging;
public class AuditService : IAuditService
{
private readonly ILogger<AuditService> _logger;
public AuditService(ILogger<AuditService> logger)
{
_logger = logger;
}
public void LogOperation(string message)
{
_logger.LogInformation($"Audit Log: {message}");
}
}
Services/PaymentGatewayClient.cs
Mariusz PostolPosted Aug 27, 2024, 3:41 PM
You said "We'll ensure that these services are efficiently managed and injected into various parts of the application using DI" - my concern is the difference between DI and plug-it concepts.
Mariusz PostolPosted Aug 27, 2024, 1:34 PM
Referring to " Dependency Injection (DI) is a core feature in .NET" my concern is that dependency injection is a concept loosely coupled with any technology including but not limited to .NET.