As currently there is lack of documentation on DI topic - Dependency Injection. What are pros/cons of using built-in DI over existing solutions like (Ninject, Autofac, StructureMap)? And what are current limitations of default dependency injection (if any)?
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
ASP.NET Core contains a built-in dependency injection mechanism. In the Startup. cs file, there is a method called ConfigureServices which registers all application services in the IServiceCollection parameter. The collection is managed by the Microsoft.
IoC Container: also known as Dependency Injection (DI) Container, it is a programming framework that provides you with an automatic Dependency Injection of your components.
There are two types of service containers provided by the ASP.net core: Framework Services and Application Services.
For product development of any reasonably sized application that practice loose coupling and follows the SOLID principles, .NET Core's DI container (MS.DI) is unsuited, because:
ValidateOnBuild
, but the only thing it does is check whether all dependencies of all registrations can be satisfied.Service1
and Service2
that both depend on ILogger
, you might want to inject Service1
with NullLogger
and Service2
with FileLogger
, or you want Service1
to be injected with Logger<Service1>
and Service2
with Logger<Service2>
.The main reason for those limitations to exist is because it's the goal of the built-in container to provide DI capabilities to especially the framework itself, while keeping its feature set to a minimum in the hope that more-mature DI containers would be able to integrate with it. In other words, it tries to act as an Least-Common Denominator (LCD). Because of its LCD function, it can never grow to a full-fledged DI Container that is practical for application development (not without breaking the promise of being an LCD).
If you start with a new and simple project, my advice is to apply Pure DI. This means you hand-wire components inside the Composition Root without using a container and without creating your own DI Container. Instead you resolve your types by plugging in your custom IControllerActivator. Later on, when features such as Auto-Wiring, Auto-Registration and Interception would improve maintainability of your Composition Root, switch to one of the established DI libraries that fits your requirements.
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