question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support dependency injection into instances

See original GitHub issue

Issue Description

I would like to the ability to inject dependencies into model instances at the point where Sequelize creates them.

Is your feature request related to a problem? Please describe.

I often find myself wanting to use dependencies (e.g. api or messaging clients) from my model instances, e.g.

static async function ensureUser(username) {
  let user = await User.findOneByCriteria({ where: { username }});
  if (user) return user;

  user = await this.userApi.fetchUserByEmail(username);
  return User.save(user);
}
// n.b. There's a race condition in the above, this is just a simple example to demonstrate the dependency issue*

I haven’t found a nice way to achieve with Sequelize because there doesn’t appear to be a way to inject dependencies into model instances.

Describe the solution you’d like

I was wondering whether a afterConstruct hook could be used to solve this. I understand it might be slow for large record sets, but hopefully not that slow if all it was doing was fetching a pre-created dependency.

function initModels(dependencies) {
  User.init({
    username: DataTypes.STRING,
  }, {
    hooks: {
      afterConstruct: (user, options) => {
        user.userApi = dependencies.userApi;
        user.messageBroker = dependencies.messageBroker
        // n.b. assignment might need to support async factories, although caution should be taken as this could be extremely slow for large record sets
      },
    },
    sequelize
    // An alternative solution might be to support a dependencies object here
  });
}

Why should this be in Sequelize

One of the primary use cases for Sequelize (or any ORM) is to support rich domain models, which collocate behaviour and state. Not being able to inject dependencies undermines this.

Describe alternatives/workarounds you’ve considered

The options I’ve considered are:

  • Requiring the dependency / using singletons. This is infeasible if the dependency has async setup or requires its own dependencies. Also makes TDD harder.
  • Passing the dependencies as arguments to the function, e.g. ensureUser(username, userApi). This adversely affects readability (by increasing the number of function arguments) and potentially means passing dependencies through several levels of function call, before they’re actually used
  • Copying the constructor approach you use for injecting this.sequelize (this is what we’re currently using as a workaround)

Additional context

Issue Template Checklist

Is this issue dialect-specific?

  • No. This issue is relevant to Sequelize as a whole.

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start (but may also benefit from guidance).

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
cressie176commented, Jan 25, 2020

Thanks @papb. We have a hackday coming up soon. We’ll work on the PR then.

1reaction
cressie176commented, Jan 17, 2020

Hi @papb, we’d be happy to work on a PR. Any thoughts about hooks not being fired for nested / included entities?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependency injection in ASP.NET Core | Microsoft Learn
NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) ...
Read more >
How to Resolve Instances With ASP.NET Core DI - Code Maze
In ASP.NET Core dependency injection, we usually register injectable dependencies at the start of our program. We can then resolve these ...
Read more >
Dependency Injection in ASP.NET Core - TutorialsTeacher
NET Core is designed from scratch to support Dependency Injection. ASP.NET Core injects objects of dependency classes through constructor or method by using ......
Read more >
Dependency Injection - new instance required in several of a ...
Inject that into MyService instead of directly injecting the original implementation (MyStatefulDependency). If you want to abstract away the ...
Read more >
Understanding Dependency Injection in .NET Core - Auth0
The IoC Container searches in its service collection a registration that can satisfy this request and passes such an instance to the controller....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found