Unable to Add Dependency to Subclassed Object

In my setup, there are three classes that interact with each other. I am utilizing inversify for handling dependency injection. However, I encountered an issue when I injected the class MessageBroker into the derived class Repository and found that the MessageBroker was undefined:

import 'reflect-metadata';
import { injectable, inject, Container, unmanaged } from 'inversify';

const container = new Container();

const registerProviders = (...providers: any[]) =>
  providers.forEach(provider => container.bind(provider.name).to(provider));

const getProvider = (provider): any => container.get(provider.name);

@injectable()
export class MessageBroker {
  start = () => console.log('init message broker');
}

@injectable()
export abstract class Repository {
  @inject(MessageBroker.name) private mb: MessageBroker;

  constructor(@unmanaged() protected readonly user: any) {}

  // this.mb is undefined
  initialize = () => this.mb.start();
}

@injectable()
export class UserRepository extends Repository {
  constructor() {
    super({ user: 'some object' });
    this.initialize();
  }
}

registerProviders(UserRepository, Repository, MessageBroker);

const repo: UserRepository = getProvider(UserRepository);

To test it yourself, you can check out the sample code on GitHub: https://github.com/flolude/stackoverflow-inversify-injected-service-undefined

Upon running the script, I encountered the following error message:

/project/index.ts:22
  initialize = () => this.mb.start();
                             ^
TypeError: Cannot read property 'start' of undefined
    at UserRepository.Repository.initialize (/project/index.ts:22:30)
    at new UserRepository (/project/index.ts:29:10)
    at _createInstance (/project/node_modules/inversify/lib/resolution/instantiation.js:21:12)
    at Object.resolveInstance (/project/node_modules/inversify/lib/resolution/instantiation.js:41:18)
    at /project/node_modules/inversify/lib/resolution/resolver.js:72:42
    at Object.resolve (/project/node_modules/inversify/lib/resolution/resolver.js:96:12)
    at /project/node_modules/inversify/lib/container/container.js:319:37
    at Container._get (/project/node_modules/inversify/lib/container/container.js:310:44)
    at Container.get (/project/node_modules/inversify/lib/container/container.js:230:21)
    at getProvider (/project/index.ts:9:50)

P.S. The same error persisted even after compiling the code to Javascript

Answer №1

The MessageBroker is currently set in memory but has not been created, resulting in the undefined error. To resolve this, you must instantiate the MessageBroker in your constructor like so:

this.mb = new MessageBroker();

Alternatively, you can also add a parameterless constructor to the MessageBroker class to achieve the same result without the above line of code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting useFieldArray to work with Material UI Select component

I am currently working on implementing a dynamic Select field using Material UI and react-hook-form. While the useFieldArray works perfectly with TextField, I am facing issues when trying to use it with Select. What is not functioning properly: The defau ...

The issue of Jquery ajax functionality not functioning properly within the Laravel 5.6 framework

Within the file assets/js/bootstrap.js, I currently have the following code: window._ = require('lodash'); window.Popper = require('popper.js/dist/umd/popper'); try { window.$ = window.jQuery = require('jquery/dist/jquery.sl ...

What is the significance of combining two arrays?

const customTheme = createMuiTheme({ margin: value => [0, 4, 8, 16, 32, 64][value], }); customTheme.margin(2); // = 8 This code snippet showcases how to define spacing values in a Material-UI theme configuration. For more details on customization re ...

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...

Please confirm the modal by adding a textarea with a newline in SweetAlert2

Every time I attempt to add a line break in the textarea input field, the modal pops up. I have tried adding these lines of code as well, but nothing seems to be working: allowEnterKey: false, focusConfirm: false, Does anyone have any advice for solving ...

Double up on your calls to the subscribe function in Angular to ensure successful login

Within my angular 7 application, there is a sign in component that triggers the sign in function within the authentication service. This function initiates an HTTP post request and then subscribes to the response. My goal is to have both the auth service f ...

The transitions on my jQuery Mobile page are not functioning correctly

I am currently working on a custom MVC structure using Handlebars and jQuery Mobile. To manually manage routing, I have disabled two jQM parameters: $.mobile.linkBindingEnabled = false; $.mobile.hashListeningEnabled = false; These lines disable link bind ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

hiding a dropdown menu in vuejs when clicking outside of it

Utilizing dropdown menu components in vuejs to create a standard dropdown menu. The code for the dropdown component is as follows: <template> <span class="dropdown" :class="{shown: state}"> <a href="#" @click.prevent="toggleDro ...

Click the link to copy it and then paste the hyperlink

I am facing an issue with copying and pasting file names as hyperlinks. I have checkboxes next to multiple files and a share button. When I check the boxes and click on the share button, I want to copy the download URLs for those files. Although I can succ ...

Leveraging ES6 import declarations within Firebase functions

I've been experimenting with using ES6 in Firebase functions by trying to import modules like "import App from './src/App.js'. However, after adding type:"module" to my package.json, I encountered a strange error with Firebase ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

Toggle the div's visibility to fade in and out once more

Apologies if this is a simple issue to resolve. My goal is to create a div that, when selected, will be replaced by another div with the option to switch back to the original div when "back" is clicked. This is my current progress: $(document).ready( ...

Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe. I believe adding ...

Display a particular div upon clicking a specific link, while concealing the other divs

As a beginner in the world of jQuery and coding, I'm encountering some difficulties that I need help with. My goal is to have the 'Vlogging' link activated and show 'Details 1' when the page loads. Then, upon clicking on either &a ...

Display the details tag in Vue when the router-link is currently active

I am trying to set the attribute "open" on a details tag when its child, specifically the <router-link>, is active. To achieve this, I have created a details tag... <!-- ...template --> <details> <summary ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

Iterating through an array with conditional statements

I am currently considering the best approach to loop through an array in my code before proceeding further. I have some concerns about the link (var link = ... ) and the if statement. Is this the most optimal way to iterate over array1 and compare the val ...

Instructions for resolving the Sys.ArgumentTypeException error: The object of type 'Object' cannot be converted to type 'Function'

I encountered a specific error in my JavaScript function that I'm struggling to resolve. Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function'. Parameter name ...