Dependency injection
In the previous code examples, we use IDbContextFactory<AppDbContext>
and AppDbContext
directly in the resolvers. In order to encapsulate our data access logic, we can add a service layer to implement our business logic. HotChocolate supports dependency injection for resolvers. In this section, we will learn how to inject other services into the resolvers.
To demonstrate how to use dependency injection in HotChocolate, we will add an interface named ITeacherService
and a class named TeacherService
, as follows:
public interface ITeacherService{ Task<Department> GetDepartmentAsync(Guid departmentId); Task<List<Teacher>> GetTeachersAsync(); Task<Teacher> GetTeacherAsync(Guid teacherId); // Omitted for brevity } public class TeacherService(IDbContextFactory<AppDbContext> contextFactory) : ITeacherService { ...