Advanced Dependency Injection Techniques in ASP.NET Core

Sasha Marfut
Geek Culture
Published in
4 min readNov 14, 2021

--

Photo by Christopher Gower on Unsplash

In this post, we’re going to explore several ASP.NET Core dependency injection techniques that are present in many complex projects but go beyond the standard DI usage patterns.

Implementing DI Factory

Sometimes it is necessary to change the implementation of an interface at runtime according to some configuration value, user input, or other variables to change the behavior of the application.

For instance, there might be a need to choose between old and new functionality based on the value of the feature flag. The very first idea of fulfilling this requirement would be to simply add a condition to the ConfigureServices method like that:

However, the demonstrated solution has certain limitations. The ConfigureServices method runs only once when the application starts. This means that changing the value of the FeatureEnabled flag will not matter until the application is restarted, which is not very flexible.

--

--

Sasha Marfut
Geek Culture

1 million+ views on Medium | .NET, Design Patterns, Architecture, API