Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

container.resolve type auto-inference feature #328

Closed
pauchiner opened this issue Jul 17, 2023 · 1 comment
Closed

container.resolve type auto-inference feature #328

pauchiner opened this issue Jul 17, 2023 · 1 comment

Comments

@pauchiner
Copy link

I've been looking for DI libraries for several days and this is the best I've found so far, but when integrating with typescript it is quite annoying to have to infer the types in each resolve:

interface Service {
  ...
}

class MyService implements Service {
  ...
}

container.register({
  service: asClass(MyService)
)

// Returns any type
container.resolve('service');

// Returns the expected type but it's quite annoying to have to put the type in every resolve
container.resolve<Service>('service');

Isn't there a way for the types to be auto-inferred in the register method?

@jeffijoe
Copy link
Owner

What you are asking for specifically is not possible since it would require chaining all registrations in order to build the type map.

The next best thing is to define a modules collection type and use that in createContainer:

interface Modules {
  service: Service
}

const container = createContainer<Modules>()
container.register({
  // This should now be typed
  service: asClass(MyService)
})

// Returns expected type
container.resolve('service');

However, .resolve (and .cradle) are usually only used for entrypoints and for library integrations, 99% of your code using Awilix will be exclusively DI, and there is no way for Awilix to guarantee that constructor(service: Service) is upheld. However, in practice I have found that is rarely (if ever) an issue.

Awilix makes that trade-off in order to not invade your codebase; in other words, your application code should not be littered with Awilix imports.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants