nest icon indicating copy to clipboard operation
nest copied to clipboard

[Question] Strange behavior with DI and factory

Open JulianRuhrDev opened this issue 9 years ago • 2 comments

Hello again,

I came across a problem where I am not sure if this is a wanted behavior regarding the injection via a factory.

I have the following module configuration:

Problem Case

@Module({
  components: [
    UserModelFactory,
    {
      provide: 'UserModel',
      useFactory: (userModelFactory: UserModelFactory) => {
        return userModelFactory.getSingletonInstance();
      },
      inject: [UserModelFactory],
    },
  ],
})
export class MongooseModelsModule {
}

In my repository layer I want to inject the mongoose model created by the factory class:

export class UserRepository implements IUserRepository {
  private readonly user: mongoose.Model<UserDocument>;

  constructor(
    @Inject('UserModel') user: mongoose.Model<UserDocument>,
  ) {
    this.user = user;
  }
}

Still I get an error message that the dependency of my repository class could not be resolved. My factory class itself is called and the model is created right.

I debugged the code and came to the following line where the problem is coming up:

    scanForComponentInRelatedModules(module, name) {
        const relatedModules = module.relatedModules || [];
        let component = null;
        relatedModules.forEach((relatedModule) => {
            const { components, exports } = relatedModule;
            // Coponents contains 'UserModel' but exports doesn't resulting in returning null
            if (!exports.has(name) || !components.has(name))
                return;
            component = components.get(name);
            if (!component.isResolved) {
                this.loadInstanceOfComponent(component, relatedModule);
            }
        });
        return component;
    }

Is it really necessary that the 'UserModel' must be within the exports metadata as I only define the component for the injection (see module above). This behavior seems strange to me.

Solution / Workaround

Doing the following Module configuration I get a working result:

@Module({
  exports: {
    UserModelFactory,
  },
  components: [
    UserModelFactory,
    {
      provide: 'UserModelFactory',
      useFactory: (userModelFactory: UserModelFactory) => {
        return userModelFactory.getSingletonInstance();
      },
      inject: [UserModelFactory],
    },
  ],
})
export class MongooseModelsModule {
}
export class UserRepository implements IUserRepository {
  private readonly user: mongoose.Model<UserDocument>;

  constructor(
    @Inject('UserModelFactory') user: mongoose.Model<UserDocument>,
  ) {
    this.user = user;
  }
}

This seems a bit awkward to me as I have to name my key the same as the class constructor AND I have to put the constructor into components and exports. Is this behavior intended?

JulianRuhrDev avatar May 09 '17 13:05 JulianRuhrDev

Hi @JulianBiermann, The DI container resolves dependencies by token. The token is a name of the type. When you use the same name of type and the custom token, there is a conflict.

However, it looks that there is an issue with custom components exporting. The problem is already resolved, just update package into 1.0.6 version.

So, if you want to export a custom component, you should do it in this way:

const UserModel = {
  provide: 'UserModel',
  useFactory: (userModelFactory: UserModelFactory) => {
    return userModelFactory.getSingletonInstance();
  },
  inject: [UserModelFactory],
}

@Module({
  exports: [
    UserModel,
  ],
  components: [
    UserModelFactory,
    UserModel,
  ],
})
export class MongooseModelsModule {}

kamilmysliwiec avatar May 09 '17 16:05 kamilmysliwiec

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Sep 25 '19 13:09 lock[bot]