I've been reading quite a lot on the concept of Inversion of Control (IoC) and Dependency Injection (DI), and I've seen that DI often relies on an IoC container, which among other roles has to
Register: The container must know which dependency to instantiate when it encounters a particular type. This process is called registration. Basically, it must include some way to register type-mapping.
Resolve: When using the IoC container, we don't need to create objects manually. The container does it for us. This is called resolution.
The above quote comes from: https://www.tutorialsteacher.com/ioc/ioc-container#:~:text=IoC%20Container%20. While I understand "Resolve", which is basically letting the IoC container create the dependency to be injected, I really cannot understand "Register". I tried my hardest to look for a language-independent explanation of registration (which is what I want, considering my limited programming experience), but I never understood the "registration" role of the container. The link above is to me one of the best links that has a language-independent overview of the IoC container, but I cannot understand it at all.
I thought the IoC container is an under-the-hood mechanism that basically creates the dependency for us whenever we include it in the constructor of the dependent class (in the constructor if we are using constructor injection).
In other words, instead of having a line of code instantiating an instance of the MsSqlConnection
, as below on 'line X
':
class User {
constructor(connection: MsSqlConnection) {}
}
class MsSqlConnection {
constructor() {}
}
const connection = new MsSqlConnection() // notice how we create the connection here; call this line X
const user = new User(connection) // line Y
we would have the IoC container do the job of creating the MsSqlConnection
instance on 'line X
', so that we can directly inject the connection
, prepared by the IoC container, into the constructor of User
on 'line Y
'. From the above example, the role of the IoC container to instantiate the object, called 'resolution', is pretty clear to me. But what about 'registration'? In this simple hard-coded example where I create the MsSqlConnection
myself on 'line X
', I'm not doing anything remotely related to "type-mapping" and "registration" in general. At least, not that I see it.
I'd be more than grateful if someone could provide a language-independent explanation of this registration process, or one in NestJS (which I'm somewhat accustomed to).