U
U
user_of_toster2021-05-01 10:45:38
SOLID
user_of_toster, 2021-05-01 10:45:38

How to do DI without violating DIP?

There is a class, in the constructor of which, in addition to a couple of arguments, dependencies should be injected. The problem is that every time you create an instance of this class, it is inconvenient to inject dependencies. The solution comes down to using IoC.

The problem is that if you use frameworks like InversifyJS, then the entire codebase is overgrown with dependencies on the framework, as a result, in an attempt to get rid of one dependency, we get another.

You can separately create index.js, which stores a class with already injected dependencies, but in the end the number of files doubles.

It is interesting how this problem is solved in practice, especially in large projects. How do you inject dependencies? Do you turn a blind eye to framework dependencies and use them? Or do you create a separate index.js in which you store a class with an already injected dependency?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-05-01
@user_of_toster

According to SOLID, it will be quite like this:

// SomeInterface.ts
export interface SomeInterface {
    /* ... */
}

// DependencyClass.ts
import type {SomeInterface} from './SomeInterface';

export class DependencyClass implements SomeInterface {
    /* ... */
}

// DependableClass.ts
import type {SomeInterface} from './SomeInterface';

export class DependableClass {
    constructor(
        private dependency: SomeInterface,
    ) {}

    /* ... */
}


// index.ts
import {DependencyClass} from './DependencyClass';
import {DependableClass} from './DependableClass';

new DependableClass(
    new DependencyClass(),
);

As Demian Smith already wrote in the comments to the question, most of the existing typescript containers do not store information about types, and therefore you can inject anything through them and typescript will believe that this is the desired type, and errors will go to runtime. (I hope this long weekend to find time to throw out my container on npm, although it is not purely OOP, I designed it to be used in any paradigm)
I also advise you to read Uncle Bob: https://www.litres.ru/robert-s -martin/chistaya-arh...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question