Skip to main content

Container Resolution

ContainerResolver

ContainerResolver is a static class in Depinjionary that simplifies dependency injection by providing a globally accessible container. It serves as the entry point for initializing and retrieving your DI container.

Features

  • Global Accessibility: The container can be accessed from anywhere in your application.
  • Initialization: Define your providers and initialize the container with them.
  • Instance Retrieval: Retrieve the initialized container whenever needed.

Usage

Below is an example of how to use ContainerResolver:

import { ContainerResolver, ContainerInterface } from 'depinjionary';
import providers from './providers'; // Your array of Provider[]

const container: ContainerInterface = ContainerResolver.init(providers);

Methods

init(providers: Provider[]): Container

This method initializes the container with the given set of providers. Once initialized, the container is globally accessible.

  • Parameters:
    • providers: An array of Provider objects defining your dependencies.
  • Returns:
    A Container instance.

get(): Container

Fetches the globally initialized container.

  • Returns:
    The current instance of the Container.

Example

Here's an example that demonstrates setting up a DI container with ContainerResolver:

import { ContainerResolver, ContainerInterface } from 'depinjionary';
import { ServiceA } from './services/serviceA';
import { ServiceB } from './services/serviceB';

// Define your providers
const providers = [
{ provide: 'ServiceA', useClass: ServiceA },
{ provide: 'ServiceB', useClass: ServiceB },
];

// Initialize the container
const container: ContainerInterface = ContainerResolver.init(providers);

// Retrieve the container and resolve dependencies
const serviceA = await container.resolve<SericeA>('ServiceA');
serviceA.doSomething();

Notes

  • Singleton Design: The ContainerResolver ensures that only one container instance is active globally.
  • Error Handling: Make sure to call init before invoking get. Calling get without initialization will result in an error.