I am learning about Dependency Injection. I understand the basic reason why it is vital when developing large applications.
It seems Dependency Injection uses reflection to achieve some of its goals. To me it seems that reflection is a kind of reverse engineering.
Why and how is Reflection used and is it optional?
One of the features that the framework 'Abathur' includes is the ability to add and remove components without recompiling the code. This feature is implemented through dependency injection and utilizes reflection.
This method uses reflection to inject the dependencies, which is costlier than constructor-based or setter-based injection. It's really easy to keep adding multiple dependencies using this approach.
But when using dependency injection (DI), we can change the Wheels at runtime (because dependencies can be injected at runtime rather than at compile time). You can think of DI as the middleman in our code who does all the work of creating the preferred wheels object and providing it to the Car class.
Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.
Dependency Injection is a design pattern with pretty good language support in most OO languages. If you define the dependencies a type needs in its constructor, you get compile-time support when you create that type in your Composition Root, i.e. it won't compile if you pass in the wrong types into the constructor.
Your confusion is probably because you think the use of Dependency Injection libraries (that use reflection) is mandatory, but it isn't. I would even argue that when starting with DI, and for small applications, you should start without such library, because the help to compiler gives you will be of great benefit.
When the application grows, you might want to switch to the use of a DI library, because it can dramatically lower the amount of maintenance on your Composition Root. When doing this you will lose compile-time support. So you should select a DI library that can compensate the loss of compile-time support (some of them contain verification and diagnostic features) and you will need to add some integration tests that allow you to verify the correctness of the configuration to compensate the loss of compile-time support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With