Skip to main content

Dependency Injection

As your application grows, managing the dependencies between your controllers and services (like database clients, logger instances, or configuration objects) can become complex.

@electron-ipc-bridge provides a flexible resolver bridge that allows you to integrate any Dependency Injection (DI) container or custom factory logic into your IPC setup. Popular choices include TypeDI, NestJS, and tsyringe.

Why use Dependency Injection?

  1. Testability: Easily swap real services for mocks during unit tests.
  2. Modularity: Decouple your controller logic from the implementation details of its dependencies.
  3. Singleton Management: Ensure that services like a Database connection are only instantiated once.

The Resolver Bridge

The createIpcApp function accepts a resolver object. This object acts as a factory for your controller instances.

Using a Simple Factory

If you don't need a full DI container, you can use a simple anonymous function to instantiate your classes:

src/main/index.ts
import UserController from "./users/user.controller";

const userController = new UserController();

const instances = {
[UserController.name]: userController,
};

const app = createIpcApp({
controllers: [UserController],
resolver: {
resolve: (ControllerClass) => instances[ControllerClass.name],
},
});

Common DI Library Bridges

Most DI containers have a way to resolve a class. The examples below are a starting point for integrating with your project's DI container:

src/main/index.ts
import { container } from './inversify.config';
import UserController from './users/user.controller';

const app = createIpcApp({
controllers: [UserController],
resolver: {
resolve: (token) => container.get(token),
},
});

We have a full example demonstrating TypeDI integration in the repository.