Nâng CaoGolang iconGolang

Dependency injection trong Go thế nào?

Dependency injection trong Go thực hiện chủ yếu qua constructor injection: function khởi tạo nhận interface làm tham số, ví dụ func NewUserService(repo UserRepository) *UserService, giúp UserService không phụ thuộc vào implementation cụ thể mà chỉ phụ thuộc vào contract (interface).

Triết lý Go ưu tiên sự tường minh nên phần lớn project không cần DI framework, chỉ cần truyền dependency thủ công tại main function. Với ứng dụng lớn nhiều dependency lồng nhau, có thể dùng wire (Google, compile-time) hoặc fx (Uber, runtime).

Interface nên giữ nhỏ (1-3 methods) theo nguyên tắc Interface Segregation, và khi viết test chỉ cần inject mock implementation vào constructor là xong.

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang