.NET Core was designed with Dependency Injection (DI) built-in to the framework. Typically, the start of a .NET Core application contains the set up of the DI for an application that primarily contains the creation of a collection of services. The framework uses these services to supply the dependencies when the application requires them. The services provide the foundation of a robust Inversion of Control (IoC) framework and are arguably one of the coolest features of .NET Core. This section will complete the console application and demonstrate how .NET Core supports building a sophisticated IoC framework based on the IServiceCollection interface.
The IServiceCollection interface is used to define the services available to the container that implements IServiceProvider interface. The services themselves are types that will be injected at runtime when required by the application. For example, ConsoleUserInterface interface, which was defined previously, will be a service injected at runtime. This is shown in the following code:
IServiceCollection services = new ServiceCollection();
services.AddTransient<IUserInterface, ConsoleUserInterface>();
In the preceding code, ConsoleUserInterface interface is being added as a service that implements the IUserInterface interface. If the DI is providing another type that requires a IUserInterface interface dependency, then ConsoleUserInterface interface will be used. For example, InventoryCommandFactory is also added to the services, as shown in the following code:
services.AddTransient<IInventoryCommandFactory, InventoryCommandFactory>();
InventoryCommandFactory has a constructor that requires an implementation of the IUserInterface interface:
public class InventoryCommandFactory : IInventoryCommandFactory
{
private readonly IUserInterface _userInterface;
public InventoryCommandFactory(IUserInterface userInterface)
{
_userInterface = userInterface;
}
...
}
Later, an instance of InventoryCommandFactory is requested, as follows:
IServiceProvider serviceProvider = services.BuildServiceProvider();
var service = serviceProvider.GetService<IInventoryCommandFactory>();
service.GetCommand("a");
Then, an instance of IUserInterface (in this application it is the registered ConsoleUserInterface) is instantiated and supplied to the constructor of InventoryCommandFactory.