csharp / intermediate
Snippet
Enabling Unit Testing via Interface Decoupling
Dependency Inversion through interfaces allows you to replace real implementations with 'mocks' during testing. This ensures that unit tests focus on the class logic rather than external dependencies like email servers.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface IEmailService {void Send(string message);}public class UserNotifier {private readonly IEmailService _service;public UserNotifier(IEmailService service) {_service = service;}public void Notify(string text) {if (!string.IsNullOrEmpty(text)) {_service.Send(text);}}}
Breakdown
1
private readonly IEmailService _service;
Stores a reference to the abstraction rather than a concrete implementation.
2
public UserNotifier(IEmailService service)
Injects the dependency through the constructor (Constructor Injection).