Add Dependency Injection example and core interfaces. Implement Inject class for managing scopes and instances, along with InstanceProvider, IntegerConstantProvider, and StringConstantProvider for dependency resolution.
This commit is contained in:
47
src/di/InstanceProvider.ts
Normal file
47
src/di/InstanceProvider.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright 2025 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
|
||||
*/
|
||||
|
||||
import {Type} from './Type';
|
||||
import type {IDependencyProvider} from './IDependencyProvider';
|
||||
|
||||
/**
|
||||
* A dependency provider for pre-existing instances.
|
||||
*/
|
||||
export class InstanceProvider implements IDependencyProvider {
|
||||
private readonly _type: Type;
|
||||
private readonly _instance: unknown;
|
||||
|
||||
constructor(type: Type, instance: unknown) {
|
||||
if (!(type instanceof Type)) {
|
||||
throw new Error('Must provide a valid type');
|
||||
}
|
||||
|
||||
if (instance === null || instance === undefined) {
|
||||
throw new Error('Must provide a valid instance');
|
||||
}
|
||||
|
||||
this._type = type;
|
||||
this._instance = instance;
|
||||
}
|
||||
|
||||
canProvide(type: Type): boolean {
|
||||
if (!(type instanceof Type)) {
|
||||
throw new Error('Must provide a valid type');
|
||||
}
|
||||
|
||||
return type.equals(this._type);
|
||||
}
|
||||
|
||||
async provide(type: Type): Promise<unknown> {
|
||||
if (!(type instanceof Type)) {
|
||||
throw new Error('Must provide a valid type');
|
||||
}
|
||||
|
||||
return this._instance;
|
||||
}
|
||||
|
||||
toString(): string {
|
||||
return 'InstanceProvider';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user