Dependency Injection

evergreenLast update on Jul 9, 2026
Download .md

Dependency Injection (DI) memudahkan testing, maintenance, dan decoupling antar layer.

Go

Gunakan uber-go/fx atau samber/do.

fx Pattern

// Module definition
var UserModule = fx.Module("user",
    fx.Provide(NewUserRepository),
    fx.Provide(NewUserService),
    fx.Provide(NewUserHandler),
)

// Provide (constructor injection)
func NewUserService(repo UserRepository) *UserService {
    return &UserService{repo: repo}
}

fx Module

Group module ke dalam internal/modules/ atau internal/domain/.

Laravel

Gunakan service container bawaan.

// Bind interface ke implementation
$this->app->bind(
    UserRepositoryInterface::class,
    EloquentUserRepository::class
);

// Inject via constructor
class UserController extends Controller
{
    public function __construct(
        private UserRepositoryInterface $users
    ) {}
}

NestJS

Gunakan module + decorator @Injectable().

@Module({
  providers: [UserService],
  controllers: [UserController],
})
export class UserModule {}

@Injectable()
export class UserService {
  constructor(private repo: UserRepository) {}
}

Aturan

  1. Interface ke implementation: Kode depend ke interface, bukan class konkret.
  2. Constructor injection: Jangan pakai property injection / setter injection.
  3. No global state: Gak boleh pakai singleton / global variable kecuali via DI container.