📎 Webclip
Having Fun with Microsoft IoC Container for .NET Core
The post walks through Microsoft’s default dependency injection container in .NET Core using a simple console app. It shows how to register services in ServiceCollection, build a ServiceProvider, and let the container create dependencies through constructor injection.
It also examines the container’s internals, including ServiceDescriptor, GetService(), and the resolution path for IEnumerable when multiple implementations are registered for the same interface.
Reading notes#
- The post aims to configure and use Microsoft’s default dependency injection container from scratch in a console application.
- It assumes the reader already understands Dependency Injection and Inversion of Control.
- The container lives in the
Microsoft.Extensions.DependencyInjectionnamespace. - The basic steps are adding the NuGet package, registering types with
ServiceCollection, and retrieving them fromServiceProvider. MyServicedepends onMyDependencythrough constructor injection.- Instantiating
MyServicedirectly withnew MyDependency()is presented as a poor approach because it makes the caller manage dependencies and lifetimes. - The example registers both services with scoped lifetime.
BuildServiceProvider()returns aServiceProviderfrom the registrations stored inServiceCollection.- The post says the container resolves and instantiates services when
GetService()is called. ServiceCollectionstoresServiceDescriptorentries that describe each registration.AddScopedadds aServiceDescriptorto the collection.- The post recommends using interfaces instead of concrete classes for registrations.
- When multiple implementations are registered for the same interface, the last registered one is the one resolved by default.
- To access multiple implementations, the consumer can inject
IEnumerable<IMyDependency>. - Only
IEnumerableis resolved this way, notIList, arrays, or other collection types. - The post notes that multiple implementations can also be handled with
TryAddEnumerable. - The resolution path uses internal call-site logic and caches inside the service provider engine.
- The container resolves an
IEnumerableby visiting each registered implementation and constructing each one. - The post mentions that Microsoft’s container covers the essentials but lacks features such as assembly scanning and decorators found in Autofac and Scrutor.
