A dependency is an object that another object depends on. Examine the following MyDependency class with a WriteMessage method that other classes depend on:

    public class MyDependency
    {
        public void WriteMessage(string message)
        {
            Console.WriteLine($"MyDependency.WriteMessage called. Message: {message}");
        }
    }
    

A class can create an instance of the MyDependency class to make use of its WriteMessage method. In the following example, the MyDependency class is a dependency of the IndexModel class:


    public class IndexModel : PageModel
    {
        private readonly MyDependency _dependency = new MyDependency();
        public void OnGet()
        {
            _dependency.WriteMessage("IndexModel.OnGet created this message.");
        }
    }
    

The class creates and directly depends on the MyDependency class. Code dependencies, such as in the previous example, are problematic and should be avoided for the following reasons:
	• To replace MyDependency with a different implementation, the IndexModel class must be modified.
	• If MyDependency has dependencies, they must also be configured by the IndexModel class. In a large project with multiple classes depending on MyDependency, the configuration code becomes scattered across the app.
	• This implementation is difficult to unit test. The app should use a mock or stub MyDependency 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. ASP.NET Core provides a built-in service container, IServiceProvider. Services are typically registered in the app's Startup.ConfigureServices method.
	• 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.
