Retrieving Services from Dependency Injection in .NET
Introduction Dependency Injection (DI) is a critical part of .NET since the .NET Core days. A simple, although powerful, DI container is included out of the box, and ASP.NET Core makes heavy use of it . I already wrote about DI in .NET a few times: .NET 8 Dependency Injection Changes: Keyed Services ASP.NET Core Inversion of Control and Dependency Injection The Evolution of .NET Dependency Resolution Dependency Injection Lifetime Validation .NET Core Service Provider Gotchas and Less-Known Features An Extended Service Provider for .NET This time I want to highlight something that people may not be aware of, even though I already mentioned it in one of my posts. Retrieving Services As you know, the DI is represented by an instance of IServiceProvider . When we want to retrieve a service we call GetService , passing it a Type , for a dynamic call, or GetService<T> , for a strongly-typed version, which just calls the other one with a cast. Now, if the service repre...