C# Clean Code: Implementing a Testable Singleton Logger with DI
This video explains how to implement a Singleton Logger with Dependency Injection (DI) in C# (0:00). The presenter highlights the disadvantages of using a static logging class, particularly in unit testing due to tight coupling (0:31). Here's a breakdown of the key points: Singleton Logger Implementation (1:05): The video demonstrates how to create a Singleton logger class, ensuring only one instance exists. This involves using a static instance variable, a private constructor, and a public property to return the instance (1:11-2:05). Thread Safety (2:46): To handle multi-threaded environments, the video shows how to make the Singleton logger thread-safe using a lock mechanism, preventing multiple threads from creating separate instances simultaneously (2:51-3:47). Dependency Injection with an Interface (4:03): The core of the video focuses on making the Singleton logger mockable for unit testing by introducing an interface (e.g., ILogger). This allows different logger implementations (e.g., ConsoleLogger, FileLogger) to be injected, making the code more flexible and testable (4:03-5:07). Practical Example (5:08): The tutorial provides a practical example of how to use the implemented ConsoleLogger and then demonstrates how to easily switch to a FileLogger by simply changing the instance, showcasing the benefits of DI (5:08-7:25).
Download
0 formatsNo download links available.