Skip to content

feat: support for asynchronous factory functions #84

Open
@slavafomin

Description

@slavafomin

Hello!

Consider a case where you have an asynchronous factory function: for example you need to make a request or read some file from the filesystem before creating an instance of the required class.

Right now, TypeDI, if supplied with the async factory function, will add the promise object to the container instead of resolving it beforehand.

I think it's a valid use case, but in order to implement it, we will probably need to change all container's call signatures to async ones, which is a very drastic change in my opinion. However, this enables some very interesting functionality.

The alternative would be to just resolve those factory functions manually during the app initialization and register instances with the container, which could be non-optimal, because we don't know if an instance some class will be actually used during program execution (sacrificing lazy-loading).

What do you think?


The manual approach looks like this:

  const dataServiceFactory = Container.get(DataServiceFactory);
  const dataService = await dataServiceFactory.create();

  Container.set({
    type: DataService,
    value: dataService
  });

Which is somewhat cumbersome and non-automatic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    flag: needs discussionIssues which needs discussion before implementation.status: has PRIssues which has a related PR closing the issue.type: featureIssues related to new features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions