My DI container class mandates that the classes to be resolved must be decorated with an @Injectable()
decorator. This is necessary for the decorated class to emit metadata and allow for further configuration, similar to how Angular DI functions (https://angular.io/guide/dependency-injection).
When attempting to register third-party classes into my container, I encounter a dilemma where I need to apply the @Injectable
decorator to classes that I am unable to modify. Consider scenarios like incorporating a logger library from node_modules that I want in my container.
Is there a way to add decorators to third-party classes? I'm exploring possibilities such as:
import {Container, Injectable} from "./Container";
import {Logger} from "@vendor/logger";
const container = new Container();
container.register(Logger, { useClass: Logger }); // not feasible due to lack of decoration on Logger
container.register(decorate(Logger, Injectable), { useClass: Logger }); // exploring options to decorate a class with a specific decorator
The current solution involves creating a decorated proxy class that extends from the real logger class. However, this approach of proxying all third-party classes seems overly burdensome.
Any innovative suggestions?
Adding more context:
The @Injectable
decorator is vital because undecorated classes fail to emit necessary metadata, making it impossible for the container to interpret and resolve dependencies. It essentially includes a metadata key in the decorated class labeled as __INJECTABLE
set to true
- when registering new services in the container, it verifies if the __INJECTABLE
flag is present and raises an error if not.
Below is an example of a proxy class:
import {Container, Injectable} from "./Container";
import {Logger as ParentLogger} from "@vendor/logger";
// Proxy
@Injectable()
class Logger extends ParentLogger {
}
const container = new Container();
container.register(Logger, { useClass: Logger });
This approach should work theoretically, but necessitates creating proxies for nearly every third-party class.