0

I am using tsyringe for Dependency Injection in react.js app created using create-react-app. I have a singleton class which is used in other class called TestRepositoryImpl.

import { singleton } from "tsyringe";

@singleton()
class SingletonClass {
    //...
}

export default SingletonClass;

Repository Class

import { autoinjectable} from "tsyringe";
import TestRepository from "../domain/TestRepository";
import SingletonClass from "./SingletonClass";

@autoinjectable()
class TestRepositoryImpl implements TestRepository {

  constructor(singletonClass: SingletonClass){}

  test(){
      console.log("Test Function");
  }
}

export default TestRepositoryImpl;

When this class is called using container. I got the following error. Class constructor cannot be invoked without new

Here is my config files. tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node", 
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "include": [
    "src"
  ]
}

dependencies

"dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.14",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "reflect-metadata": "^0.1.13",
    "tsyringe": "^4.7.0",
    "typescript": "^4.9.5",
    "web-vitals": "^2.1.4"
}

I have tried replacing autoinjectable with singleton from TestRepositoryImpl class. Then it throws an type info not known error. I have also replaced tsyringe with inversify and it was not working.

Akash
  • 1
  • 2
  • Hy, welcome to Stack Overflow, please [don't upload text, table or error message as image](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors/285557#285557). Edit your question to contain all the information in text form - consider to use the editor's formatting options. Also see [How to Ask](https://stackoverflow.com/help/how-to-ask) – Daxelarne Mar 08 '23 at 11:50
  • Yes, thanks for the review, I have made the changes. – Akash Mar 08 '23 at 11:53
  • If you are using CRA, you will not be able to use tsyring without ejecting. I recommend trying `iti` + `iti-react` packages. I wrote them just for that – Nick Olszanski Mar 19 '23 at 20:22

0 Answers0