Search code examples
typegraphqltsyringe

How to use TypeGraphQL with tsyringe


I have a project using tsyringe and a RESTFul API. Now i should to add a GraphQL API using the type-graphql but in our documentation no have some example using it.

Is possiblem to use tsyringe to make DI with TypeGraphQL?


Solution

  • Yes, it's possible!
    Most IOC containers have the get function to retrieve an instance of the given class type. tsyringe instead have the resolve function.
    Therefore, you have to change the container option when building the schema to instruct type-graphql how to retrieve (get) a class instance from a class type:

    import { container } from 'tsyringe';
    
    const schema = await buildSchema({
      // ...
      container: { get: (cls) => container.resolve(cls) }
    });