IoC - izznogooood/dotnet-wiki GitHub Wiki

.NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies, see the article on MVVM and IoC.

Hard-coded dependencies, are problematic and should be avoided for the following reasons:

  • To replace the dependency with a different implementation, the client class must be modified.
  • If the dependant object has dependencies, they must also be configured by the client class. In a large project with multiple classes depending on some resource, the configuration code becomes scattered across the app.
  • This implementation is difficult to unit test. The app should use a mock or stub the dependant class, which isn't possible with this approach.

Dependency injection addresses these problems through:

  • The use of an interface or base class to abstract the dependency implementation.
  • Registration of the dependency in a service container. .NET provides a built-in service container, IServiceProvider. Services are typically registered at the app's start-up and appended to an IServiceCollection. Once all services are added, you use BuildServiceProvider to create the service container.
  • Injection of the service into the constructor of the class where it's used. The framework takes on the responsibility of creating an instance of the dependency and disposing of it when it's no longer needed

IoC is described in great detail in the following articles: