#Implementing registerAsync in a Dynamic Module for dynamic provider injection

7 messages · Page 1 of 1 (latest)

ornate night
#

I'm building a SutModule that loads a provider to mock all outgoing requests during resilience testing. This module uses nock to disable network connections, allowing us to control network blocking through configuration.

@Module({})
export class SutModule {
    static register(options: SutOptionsType): DynamicModule {
        const providers: Provider[] = [];

        if (options.enabled) {
            nock.disableNetConnect();
            providers.push(SomeMockSerivce);
        }

        return {
            module: SutModule,
            providers: providers,
            exports: providers,
        };
    }
}```

I have successfully implemented a `register` method that can be called like this:
```typescript
SutModule.register({ enabled: true });

This approach works, but I want to use an async configuration setup to dynamically set enabled based on ConfigService. My goal is to enable this configuration style:

SutModule.registerAsync({
    inject: [ConfigService],
    useFactory: (configService: ConfigService) => {
        return { enabled: configService.get('SYSTEM_UNDER_TEST') };
    },
});

Could someone help me understand how to implement a registerAsync method in the module to achieve this? Specifically, I’m looking for guidance on handling the async registration and injecting the ConfigService. Thank you!

south blade
ornate night
#

Thanks @south blade . I'm using ConfigurableModuleBuilder. My question is not about registerAsync in general. it's for a specific use. I want to control the providers array based on configuration.

south blade
#

as I said, you can see how others libs are implementing that registerAsync
It just a normal dynamic module, nothing fancy

#

so if you truly understood how dynamic modules works, you should be able to implement a registerAsync from scratch

pallid swallow
#

It's not possible to dynamically register an injection token, all injection tokens must be known synchronously at module creation. The only dynamic part can be the implementation behind these tokens.

#

That is, if you can provide configuration synchronously (like process.env, or state defived from it), then you can conditionally enable/disable the providers (tokens), but you can't use a provider from the DI to conditionally register another one