What is the process for generating an injected and a const object instance?

How can an instance of class A obtain a dependency on an instance of class O, while remaining a singleton for others?

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<B>( O ).to( O );
container.bind<B>( A ).toConstantValue( A ); // ?
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);

Answer №1

Unable to locate the information in the official documentation, but one possible solution is suggested here -

@injectable()
class O{}

// A must be single instance!
@injectable()
class A{
    constructor(o: O){
        console.log( 'is A instance' );
    }
}
@injectable()
class B{
    constructor(a: A){
        console.log( 'is B instance' );
    }
}
@injectable()
class C{
    constructor(a: A){
        console.log( 'is C instance' );
    }
}
@injectable()
class D{
    constructor(b: B, c: C){
        console.log( 'is D instance' );
    }
}


let container = new Container();
container.bind<O>( O ).to( O );
container.bind<A>( A ).to( A ).inSingletonScope();
container.bind<B>( B ).to( B );
container.bind<C>( C ).to( C );
container.bind<D>( D ).to( D );

container.get<D>(D);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Angular 7's innovative method for handling singleton instances: Dynamic provider

In my Angular application, I have the ability to display lists of videos or articles along with their details. There are two main components: ContentListPage and ContentDetailsPage, which serve the same purpose for both videos and articles. The only diff ...

Utilizing a string variable as a property name for dynamic typing

I am looking to dynamically create a type with a property name based on specified parameters. Although I can successfully create the object, I am facing challenges when trying to create the actual type. This dynamic type creation is essential for compositi ...

What is the best way to recycle a single modal in Ionic?

Apologies for the vague title, but I'm facing an issue with creating a single modal to display data from multiple clickable elements, rather than having separate modals for each element. For example, when I click on item 1, its data should be shown in ...

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

Using Regular Expressions as an Alternative to Conditionals

My knowledge of RegEx is limited, but I'm trying to make the following expression work with Javascript/Typescript: /^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$/i This RegEx is used to check if a str ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

Discovering the most efficient route between two locations within a grid of values

I'm currently working on a game where I need to find the shortest route between two points. In my map, I have a 2D array called matrix: Node[][], class Node{ index: { x: number, y: number }, isAvailable: boolean } The goal is to ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Can someone guide me on configuring Material-UI DataGrid in React to have multiple headers with column span?

Is there a way to achieve multiple headers with column span in the Material-UI DataGrid component? view image example ...

What is the solution for resolving the error related to converting implicit any type to index type in TypeScript?

Can you help with fixing this issue? "How do I resolve the error: 'Element implicitly has an 'any' type because expression of type 'any' can't be used to index type?' " What could be causing this problem? Can you expla ...

Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads. The first input should have a value that is seven days prior to today's date, while the ...

How to Generate a Unique URL in Angular 7 Using Typescript

I'm struggling to display or download a .pdf file in my Angular 7 project due to issues with window.URL.createObjectURL. Here's the code snippet I've written: this.userService.getFile(report.id).subscribe( res => { console.log(res) ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

Displaying Firebase values in an Angular 2 list is a breeze

Here is the functionality to load, add, and mark ToDo as Finished: todos: FirebaseListObservable<any>; ngOnInit(){ this.todos = this._af.database.list('todos') } addTodo(newTodo: string){ this.todos.push({ ...

Is it possible to find a more efficient approach than calling setState just once within useEffect?

In my react application, I find myself using this particular pattern frequently: export default function Profile() { const [username, setUsername] = React.useState<string | null>(null); React.useEffect(()=>{ fetch(`/api/userprofil ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

Retrieve the attribute from a TypeScript union data type

Here is the structure that I am working with: export interface VendorState extends PaginationViewModel { vendors: CategoryVendorCommand[] | CategoryVendorCommand; } This is my model: export interface CategoryVendorCommand { id: string; name: str ...