Still memorizing the concept of dependency injection? Why not write your own dependency injection framework?
This article introduces the core implementation and testing process of KDI, a custom Dependency Injection (DI) framework built with C#. KServiceProvider registers services by iterating through KServiceCollection. For the Transient lifetime, it uses Func delegates to ensure a new instance is created every time a service is requested. For the Singleton lifetime, it leverages Lazy objects to implement lazy loading while guaranteeing global uniqueness. Through Guid service tests, the correctness of both lifetimes was verified: Singleton returns the same instance on multiple requests, whereas Transient returns a different instance each time. The article concludes with a profound critique of exam-oriented programming learning mindsets, pointing out that Scoped and Singleton behaviors have fundamental differences in console applications. Blindly applying interview techniques can lead to misunderstandings of underlying principles. The author emphasizes the importance of deeply understanding Dependency Injection mechanisms rather than rote memorization, and reminds readers to be aware of the security risks associated with the Service Locator pattern in production environments, as well as the room for improvement in the framework. Developers are encouraged to abandon rigid thinking and cultivate genuine creativity.