Skip to content
Back to skills

Nestjs Dependency Injection

ASecurity

> Master NestJS DI container with tokens, useClass/useValue/useFactory providers

  • 20 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added September 11, 2026
businesstypescriptnodetestingdatabase

Works with

  • cli

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned September 11, 2026

npx -y skills add Intense-Visions/harness-engineering --skill nestjs-dependency-injection --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Nestjs Dependency Injection?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Nestjs Dependency Injection
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/intense-visions-nestjs-dependency-injection/badge)](https://www.skillsdirectory.com/skills/intense-visions-nestjs-dependency-injection)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
# NestJS Dependency Injection

> Master NestJS DI container with tokens, useClass/useValue/useFactory providers

## When to Use

- You need to provide an interface implementation that is swappable (e.g., a real database vs. an in-memory mock)
- You need to inject a plain value (config object, constant, SDK client instance) that is not a class
- You need to run async initialization before a provider is usable (factory providers with async/await)
- You want to understand why "Cannot resolve dependencies" errors occur

## Instructions

1. **Standard provider (shorthand):** `providers: [MyService]` — NestJS creates one singleton instance, injected by class type.

2. **useClass — swap implementations:**

```typescript
providers: [
  { provide: MyService, useClass: process.env.NODE_ENV === 'test' ? MockMyService : MyService },
];
```

3. **useValue — inject constants or SDK clients:**

```typescript
export const STRIPE_CLIENT = 'STRIPE_CLIENT';

providers: [
  { provide: STRIPE_CLIENT, useValue: new Stripe(process.env.STRIPE_KEY!) }
]

// inject with @Inject token
constructor(@Inject(STRIPE_CLIENT) private stripe: Stripe) {}
```

4. **useFactory — async initialization:**

```typescript
providers: [
  {
    provide: DATABASE_CONNECTION,
    useFactory: async (config: ConfigService): Promise<DataSource> => {
      const ds = new DataSource({ url: config.get('DATABASE_URL') });
      await ds.initialize();
      return ds;
    },
    inject: [ConfigService],
  },
];
```

5. **InjectionToken vs string tokens:** Prefer `Symbol`-based or class-based tokens over plain strings to avoid collisions:

```typescript
export const MAIL_OPTIONS = new InjectionToken<MailOptions>('MailOptions');
```

6. **Inject in constructor with `@Inject(TOKEN)`** when the token is not a class:

```typescript
constructor(@Inject(MAIL_OPTIONS) private options: MailOptions) {}
```

7. **Optional injection:** Use `@Optional()` when a provider may not be registered: `constructor(@Optional() @Inject(CACHE) private cache?: Cache) {}`.

## Details

NestJS uses a hierarchical IoC container built on top of Reflect metadata. When you add a class to `providers`, the container reads its constructor parameter types via TypeScript's `emitDecoratorMetadata` and resolves each dependency recursively.

**Token resolution:** A provider token can be a class, a string, a Symbol, or an `InjectionToken<T>`. The container matches the `provide` key to the `@Inject()` token (or the constructor type for class providers). Mismatched tokens are the second most common DI error after missing exports.

**Scopes and singleton behavior:** Default (singleton) scope means `useFactory` runs once at app startup. `REQUEST` scope runs the factory (or constructor) per request — useful for per-request database connections or tenant-aware clients.

**Testing:** `overrideProvider(MyService).useValue(mockService)` in `Test.createTestingModule()` replaces any token with a mock without touching the module graph. This is the cleanest way to unit-test controllers and services.

**`ModuleRef.resolve()` for dynamic resolution:** When you need to resolve a provider at runtime (e.g., strategy pattern where the concrete implementation depends on runtime data), inject `ModuleRef` and call `moduleRef.resolve(SomeService)`.

## Source

https://docs.nestjs.com/fundamentals/custom-providers

## Process

1. Read the instructions and examples in this document.
2. Apply the patterns to your implementation, adapting to your specific context.
3. Verify your implementation against the details and edge cases listed above.

## Harness Integration

- **Type:** knowledge — this skill is a reference document, not a procedural workflow.
- **No tools or state** — consumed as context by other skills and agents.

## Success Criteria

- The patterns described in this document are applied correctly in the implementation.
- Edge cases and anti-patterns listed in this document are avoided.

Files in this skill

  • SKILL.md3.9 KB
  • skill.yaml787 B

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments

Loading comments…